24

I have double-y-axis chart made in Excel. In Excel it requires only basic skills. What I'd like to do is to replicate this chart using the ggplot2 library in R.

enter image description here

I have already done this, but I need to plot Response on 2nd-y-axis.

enter image description here

I enclose reproducible code I've used:

#Data generation
Year <- c(2014, 2015, 2016)
Response <- c(1000, 1100, 1200)
Rate <- c(0.75, 0.42, 0.80)

df <- data.frame(Year, Response, Rate)

#Chart
library(ggplot2)

ggplot(df)  + 
  geom_bar(aes(x=Year, y=Response),stat="identity", fill="tan1", colour="sienna3")+
  geom_line(aes(x=Year, y=Rate),stat="identity")+
  geom_text(aes(label=Rate, x=Year, y=Rate), colour="black")+
  geom_text(aes(label=Response, x=Year, y=0.9*Response), colour="black")
Mus
  • 7,290
  • 24
  • 86
  • 130
AK47
  • 1,318
  • 4
  • 17
  • 30

2 Answers2

39

First, scale Rate by Rate*max(df$Response) and modify the 0.9 scale of Response text.

Second, include a second axis via scale_y_continuous(sec.axis=...):

ggplot(df)  + 
    geom_bar(aes(x=Year, y=Response),stat="identity", fill="tan1", colour="sienna3")+
    geom_line(aes(x=Year, y=Rate*max(df$Response)),stat="identity")+
    geom_text(aes(label=Rate, x=Year, y=Rate*max(df$Response)), colour="black")+
    geom_text(aes(label=Response, x=Year, y=0.95*Response), colour="black")+
    scale_y_continuous(sec.axis = sec_axis(~./max(df$Response)))

Which yields:

enter image description here

setempler
  • 1,681
  • 12
  • 20
  • 6
    Hello, how can I change the limits of the secondary y axis? I am trying to create a similar graph with percentage (already multiplied by 100) and the scale on the secondary graph is not appropriate. Thanks! – user3047435 Jan 18 '18 at 23:51
  • 2
    I had the same problem as @user3047435. A lot of things I tried messed up the scaling, so for e.g. the Rate would be right but the Response was thrown out. Ultimately, I ended up taking the original percentage back down to being divided by 100, but then multiplied it again in the scaling, like so: `scale_y_continuous(sec.axis = sec_axis(~./max(df$Response)*100))`. – Jaccar Feb 05 '19 at 15:04
-1

Use the syntax label=scales::percent to make the secondary axis into percentage : Click Here for Output

library(ggplot2)
ggplot(df)  + 
  geom_bar(aes(x=Year, y=Response),stat="identity", fill="tan1", 
  colour="sienna3")+
  geom_line(aes(x=Year, y=Rate*max(df$Response)),stat="identity")+
  geom_text(aes(label=Rate, x=Year, y=Rate*max(df$Response)), colour="black")+
  geom_text(aes(label=Response, x=Year, y=0.95*Response), colour="black")+
  scale_y_continuous(sec.axis = sec_axis(~./max(df$Response),label=scales::percent))