-1

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!

  • *"it keeps showing error"* ... *which error*? There are many errors in R, many even in just `ggplot2`, please don't make us guess. (Also, we don't have your data. Please see https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info, then come back and [edit] your question to provide reproducible data and the error text.) – r2evans Oct 25 '21 at 01:18
  • I just edited it. Thanks! – HyunJu PARK Oct 25 '21 at 01:33
  • We cannot copy data from an image. You should share data in a reproducible format which can be easily copied. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269) – Ronak Shah Oct 25 '21 at 04:24
  • I didn't notice that you add data. I add code for your data, you may check it out. – Park Oct 25 '21 at 06:22
  • Does this answer your question? [ggplot with 2 y axes on each side and different scales](https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales) – tjebo Oct 25 '21 at 16:01

1 Answers1

0

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

Park
  • 14,771
  • 6
  • 10
  • 29