ggplot一般不用来画双坐标,有些图双坐标结合起来看比较好,比方说条形图和柱状图。
1.画双坐标要用到函数scale_y_continuous,这个函数规定次坐标与主坐标的换算关系,用 sec_axis(~./57.69231)来设置,其中57.69231这个换算系数可以根据实际情况调整;
2.画了双坐标,需要指定谁在次坐标上显示,那么在次坐标要缩小的倍数,在需要显示在次坐标的数据就需要提升多少倍,这样的话,才能正常显示。
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)) +
geom_line(aes(y = X2*57.69231)) +
scale_y_continuous(sec.axis = sec_axis(~./57.69231, name = "percent"))
执行结果:
如果在geom_line这行代码去除*57.69231,执行图片异常:
geom_line(aes(y = X2)) +