0

I have the below data set and want to create a Dual Axis Graph using R (ggplot2)

Header  Header  Header
Year    Revenue % change
2016    13  0%
2017    20  54%
2018    25  25%

Horizontal axis should have "Year". Primary Vertical axis should have "Revenue" in form of "Bars". Secondary Vertical axis should have "% change" in form of "line".

user20650
  • 24,654
  • 5
  • 56
  • 91
Mr.Data
  • 67
  • 1
  • 1
  • 6
  • Have you tried anything ? ... http://stackoverflow.com/questions/26917689/how-to-use-facets-with-a-dual-y-axis-ggplot/40746716#40746716 – user20650 Dec 10 '16 at 21:28
  • Yes I did:ggplot(data=yr, aes(x=year,y=revenue))+geom_bar(stat="identity"). ggplot(data=perchge, aes(x=year,y=chge))+geom_point(size=5). now, i need to combine these plots into one plot – Mr.Data Dec 10 '16 at 22:05
  • I broke the data frame into 2 separate data frames: data=yr (which has year, revenue) and data=perchge (which has year, % change). i applied ggplot command to each of these data frames and stored the graph into variable t and u. Now i tried doing t+u but it gives me error. I dont want to use facets – Mr.Data Dec 10 '16 at 22:09
  • Actually i just looked at your data.... I dont see how you can do this. The yaxis scale should be monotonic, however 2018 has the highest revenue, but doesnt have the highest change. As an alternative, perhaps use labels?? or % change from 2016 if you want to do the second axis? – user20650 Dec 10 '16 at 22:37
  • So using the second approach (ie % change is `(yr$revenue - yr$revenue[1]) / yr$revenue[1]`) . `ggplot(data=yr, aes(x=year,y=revenue))+ geom_bar(stat="identity") + scale_y_continuous(sec.axis = sec_axis(trans = ~ (. - min(yr$revenue)) / min(yr$revenue), name = '% change'))` – user20650 Dec 10 '16 at 22:38
  • from 2016 to 2017, 13 to 20 represents increase of 54%. from 2017 to 2018, 20 to 25 represents increase of 25%. That is how the percentages are derived. – Mr.Data Dec 10 '16 at 23:47
  • Hi, Mr. Data, yup i realised how they were calculated, but my suggestion was incorrectly based on the dual axis being for only barplot (as I didn't read your question correctly ;P). That said, I was trying to show an alternate approach as using annual percentage change , imo, may be slightly confusing superimposed on a barplot: take for example, if 2018's revenue had been 19, (then % change is -5%), things start to get tricky, as far as adding these points to a barplot. – user20650 Dec 11 '16 at 00:00

1 Answers1

0

Using base R, assuming your data frame is named DF...and your columns are x, y, y2. Substitute your variables...It may not like the space in "% change"...

plot(DF$y~DF$x)
points(DF$y2~DF$x,col="red")
axis(4,DF$y2)
JakeG
  • 71
  • 4