ggplot2在scale_y_continuous函數提供了右側y軸坐標sec.axis顯示選項,但如果不同量綱的數據需要展示在同一面板上則需要對其進行轉換。
通過 scale兩組數據的最大值,達到轉換數據的目的,最后在同一界面展示不同量綱的兩組數據
library(ggplot2)
data(mtcars)
scaleFactor <- max(mtcars$cyl) / max(mtcars$hp)
ggplot(mtcars, aes(x=disp)) +
geom_smooth(aes(y=cyl), method="loess", col="blue") +
geom_smooth(aes(y=hp * scaleFactor), method="loess", col="red") +
scale_y_continuous(name="cyl", sec.axis=sec_axis(~./scaleFactor, name="hp")) +
theme(
axis.title.y.left=element_text(color="blue"),
axis.text.y.left=element_text(color="blue"),
axis.title.y.right=element_text(color="red"),
axis.text.y.right=element_text(color="red")
)