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?

6
  • Take a look here. The second example should help you achieve your goal. Commented Apr 9, 2021 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. Commented Apr 9, 2021 at 20:24
  • If you don't want to transform sec.axis = sec_axis(~./1, name="Second Axis") should work. Commented Apr 9, 2021 at 20:31
  • 2
    this is one of the most asked questions with the ggplot2 tag. stackoverflow.com/questions/3099219/… Commented Apr 9, 2021 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. Commented Apr 9, 2021 at 22:29

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.