美文网首页
R可视化:同一面板展示不同刻度线条

R可视化:同一面板展示不同刻度线条

作者: 生信学习者2 | 来源:发表于2021-01-20 10:20 被阅读0次

    ggplot2在scale_y_continuous函数提供了右侧y轴坐标sec.axis显示选项,但如果不同量纲的数据需要展示在同一面板上则需要对其进行转换。更多知识分享请到 https://zouhua.top/

    通过 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

    参考文章如引起任何侵权问题,可以与我联系,谢谢。

    相关文章

      网友评论

          本文标题:R可视化:同一面板展示不同刻度线条

          本文链接:https://www.haomeiwen.com/subject/vrohzktx.html