楼主先试着绘制一个折柱混合图,然而不知道为撒主Y轴的范围跟次Y轴一样,代码如下:
library(ggplot2)
library(data.table)
data(diamonds)
diamonds.new <- as.data.table(diamonds)
diamonds.new2 <-
diamonds.new[, by = .(cut), .(y1 = median(carat), y2 = median(price))]
ggplot(data = diamonds.new2, aes(x = cut)) +
geom_bar(aes(y = y1), stat = 'identity', position = 'dodge') +
geom_line(aes(y = y2), group = 1) +
scale_y_continuous(
name = "主Y轴",
sec.axis = sec_axis(~ . , name = "次Y轴")
)
接着又试着干脆画两个双Y轴的柱状图,然后也不知为撒,只剩下一种柱子,代码如下:
ggplot(data = diamonds.new2, aes(x = cut)) +
geom_bar(aes(y = y1, fill = 'red'), stat = 'identity', position = 'dodge') +
geom_bar(aes(y = y2, fill = 'green'), stat = 'identity', position = 'dodge') +
scale_y_continuous(name = "主Y轴", sec.axis = sec_axis( ~ . , name = "次Y轴"))