0

I'm trying to create a bar-line graph in ggplot, where the bars are one distinct variable, and the line is another. These variables are not related to one another, i.e. variable2 is not based on same calculation involving variable1. My code:

#Data generation
YearMonth <- c('2014-01', '2014-02', '2014-03','2014-04','2014-05','2014-06','2014-07','2014-08')
Variable1 <- c(100, 210, 139, 245, 345, 200, 145, 450)
Variable2 <- c(3, 4, 5, 10, 12, 6, 5, 15)

df <- data.frame(YearMonth , Variable1, Variable2)

#Convert YearMonth to date in order to plot on X-axis

df$YearMonth <-as.Date(paste0(df$YearMonth, ('-01')), format="%Y-%m-%d")


ggplot(df)  + 
  geom_bar(aes(x=YearMonth, y=Variable1),stat="identity", fill="tan1", colour="sienna3") +
  geom_line(aes(x=YearMonth, y=Variable2),stat="identity")+
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

While I can get both the bars and line to display, it's the second-axis that's problematic. I tried adding scale_y_continuous parameter, but it seems like that needs to be based on some sort of relationship to variable1, which variable2 does not have.

Is this possible to accomplish in ggplot?

halfer
  • 19,824
  • 17
  • 99
  • 186
DiamondJoe12
  • 1,879
  • 7
  • 33
  • 81
  • Take a look [here](https://www.r-graph-gallery.com/line-chart-dual-Y-axis-ggplot2.html). The second example should help you achieve your goal. – Till Apr 09 '21 at 20:19
  • Correct me if I'm wrong, but all those examples listed involve a transformation of the first variable, which is not applicable to my example. – DiamondJoe12 Apr 09 '21 at 20:24
  • If you don't want to transform `sec.axis = sec_axis(~./1, name="Second Axis")` should work. – Till Apr 09 '21 at 20:31
  • 2
    this is one of the most asked questions with the ggplot2 tag. https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales – tjebo Apr 09 '21 at 21:18
  • Try replacing the `geom_line` line with these two: `geom_line(aes(x=YearMonth, y=Variable2*20),stat="identity")+ scale_y_continuous(sec.axis = sec_axis(~./20)) +` This will stretch your values for the line to be 20x as high, and then you can do the inverse to the secondary scale so that it relates to the original values. – Jon Spring Apr 09 '21 at 22:29
  • Thanks Jon! What does the (~./20)) mean? – DiamondJoe12 Apr 12 '21 at 14:05

0 Answers0