R可視化:同一面板展示不同刻度線條

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

Reference

  1. ggplot with 2 y axes on each side and different scales
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
禁止轉載,如需轉載請通過簡信或評論聯系作者。

推薦閱讀更多精彩內容