0

I would like to plot my data using 2 different y axis. There have been similar questions but the solution doesn't work for me.

my data is similar to this:

d<- data.frame(location = c("Italy", "Italy", "Germany","Germany", "France", "France"),
               label = c("Test","Control","Test","Control", "Test","Control"),
               a = c(2000,3000, 3000, 4000, 2500, 3500),
               b = c(1.5,2,2.5,2, 1.8, 3))

For now this is my solution:

p <- ggplot(d, aes(x = location))
p <- p + geom_bar(aes(y = a, fill = label, group = label, colour = label), stat = "identity",position = "dodge")
p <- p +geom_line(aes(y = b, group = label, colour = label), stat="identity", size = 0.8)+ geom_point(aes(y = b, group = label, colour = label), stat="identity")
p <- p + scale_y_continuous(sec.axis = sec_axis(~ . /2000, name = "b"))+ scale_color_manual(values=c('#7E261A','#15656A'))

I need to compare the values between Test and control group, which is hwy I am using group = label, colour = label), stat="identity" However, the secondary metric(b) does't show as intended.

enter image description here

Sakura
  • 57
  • 2
  • 8

1 Answers1

1

the problem is that you still need to scale your data because you can only use one base plot. In this post Hadley gives good reasons not to use it. ggplot with 2 y axes on each side and different scales

enter image description here

library(ggplot2)
d<- data.frame(location = c("Italy", "Italy", "Germany","Germany", "France", "France"),
               label = c("Test","Control","Test","Control", "Test","Control"),
               a = c(2000,3000, 3000, 4000, 2500, 3500),
               b = c(1.5,2,2.5,2, 1.8, 3))


p <- ggplot(d, aes(x = location))+
  geom_bar(aes(y = a, fill = label, group = label, colour = label), 
           stat = "identity",position = "dodge")+
  geom_line(aes(y = b*1000, group = label, colour = label), size = 0.8)+
  geom_point(aes(y = b*1000, group = label, colour = label), stat="identity")+
  scale_y_continuous(sec.axis = sec_axis(~ . /1000, name = "b"))+ 
  scale_color_manual(values=c('#7E261A','#15656A'))

p
  • Hadley went to great lengths to prevent this kind of dual-axis plot using ggplot because of the likelihood of confusion. Better to scale (this answer) or use facets and scale = "free_y" – Dan Slone Oct 23 '19 at 16:01
  • But label the axes much better. As-is it is very confusing. – Dan Slone Oct 23 '19 at 16:03