繁体   English   中英

如何在ggplot2中制作双y轴

[英]how to make dual y-axis in ggplot2

这是我的数据,

在此处输入图片说明

我试图在 ggplot 中制作双 y 轴,

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"))

但它一直显示错误。

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

这是我的图表

在此处输入图片说明

我想让它成为双 y 轴。 有什么帮助吗? 谢谢!

你可以试试这个方法

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"))

在此处输入图片说明

请注意, 57.69231是从

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM