pplot2做双y轴图
创建示例数据
我们将使用以下数据作为本 R 教程的基础。
set.seed(93756) # Create example data
x <- rnorm(50)
y <- x + 0.3 * rnorm(50)
data <- data.frame(x, y)
关键函数是 sec_axis,这个是双坐标系:
ggplot(data, aes(x, y)) + # Create ggplot2 plot
geom_point()+ scale_y_continuous( "Kilometers", sec.axis = sec_axis(~ . * 1000, name = "Meters") )

使用双Y轴同时显示不同范围的数值系列:
coeff <- 10 # 将数据缩放到同样的范围
ggplot(data, aes(x=day)) + geom_line( aes(y=temperature)) + geom_line( aes(y=price /coeff)) + scale_y_continuous(name = "First Axis",
sec.axis = sec_axis(~.*coeff, name="Second Axis") )
# 在轴显示是尺寸要恢复
