Home > Software engineering >  how to make dual y-axis in ggplot2
how to make dual y-axis in ggplot2

Time:10-25

Here's my data,

year item X1 percent
2017 A 475 81.896
2017 B 580 81.896
2018 A 801 71.2
2018 B 1125 71.2
2019 A 590 62.1707
2019 B 949 62.1707
2020 A 646 29.949
2020 B 2157 29.949

I tried to make dual y-axis in ggplot,

ggplot(df, aes(x = year, y = X1, fill = item))  
   geom_bar(stat = 'identity', position = 'dodge2')  
   geom_line(aes(x = year, y = percent))  
   scale_y_continous(sec.axis = sec_axis(~.*percent, name = "percent"))

but it keeps showing error.

Error: transformation for secondary axes must be monotonic Run `rlang::last_error()` to see where the error occurred.

Here's my graph

enter image description here

I want to make it as dual y-axis(bar graph for X1, line graph for percent). Any help? Thanks!

CodePudding user response:

You may try this way

dummy <- data.frame(item = c("X","X","X","X","Y","Y","Y","Y"),year = c(2017,2018,2019,2020,2017,2018,2019,2020),
                    X1 = c(500,900,600,700,700,1200,900,1500),
                    X2 = c(15,18,23,11,26,23,13,15)
                    )

ggplot(dummy, aes(x = year, group = item, fill = item, color = item))  
  geom_bar(aes(y = X1), stat = "identity", position = 'dodge2')  
  geom_line(aes(y = X2*57.69231))  
  scale_y_continuous(sec.axis = sec_axis(~./57.69231, name = "percent"))

enter image description here

note that 57.69231 is obtained from

max(dummy$X1)/max(dummy$X2)
[1] 57.69231

For df data.

ggplot(df, aes(x = year, group = item, fill = item, color = item))  
  geom_bar(aes(y = X1), stat = "identity", position = 'dodge2')  
  geom_line(aes(y = percent*26.33828))  
  scale_y_continuous(sec.axis = sec_axis(~./26.33828, name = "percent"))

enter image description here

  • Related