代码之家  ›  专栏  ›  技术社区  ›  Indrajeet Patil

使用双y轴将计数和比例添加到ggplot2的直方图中

  •  1
  • Indrajeet Patil  · 技术社区  · 7 年前

    我试图创建一个直方图,其中计数和相对频率(或比例)数据都显示在y轴上,前者显示在左y轴上,后者显示在右y轴上。

    # loading necessary libraries
    library(ggplot2)
    library(scales)
    
    # attempt to display both counts and proportions
    ggplot2::ggplot(
      data = datasets::ToothGrowth,
      mapping = ggplot2::aes(x = len)
    ) +
      ggplot2::stat_bin(
        col = "black",
        alpha = 0.7,
        na.rm = TRUE,
        mapping = ggplot2::aes(
          y = ..count..
        )
      ) +
      ggplot2::scale_y_continuous(
        sec.axis = ggplot2::sec_axis(trans = ~ (.)/sum(.),
                                     labels = scales::percent,
                                     name = "proportion (in %)")
      ) +
      ggplot2::ylab("count") +
      ggplot2::guides(fill = FALSE)
    #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
    

    如果创建另一个柱状图,只显示比例数据,这一点就很清楚了。

    # just displaying proportion
    ggplot2::ggplot(
      data = datasets::ToothGrowth,
      mapping = ggplot2::aes(x = len)
    ) +
      ggplot2::stat_bin(
        col = "black",
        alpha = 0.7,
        na.rm = TRUE,
        mapping = ggplot2::aes(
          y = ..count.. / sum(..count..)
        )
      ) +
      ggplot2::scale_y_continuous(labels = scales::percent) +
      ggplot2::ylab("proportion (in %)") +
      ggplot2::guides(fill = FALSE)
    #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
    

    我的猜测是我正在使用的转换函数 sec_axis 功能不正确。但我不知道还有什么别的办法。如果能提供帮助,我将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  1
  •   shiro    7 年前

    因为每根杆的高度都要除以同一个数,所以可以预先计算分母( tot_obs ,并调用 trans 功能:

    library(ggplot2)
    library(scales)
    
    
    # data
    df <- datasets::ToothGrowth
    
    # scalar for denominator
    tot_obs <- nrow(df)
    
    ggplot(data = df, mapping = aes(x = len)) +
      geom_histogram() +
      scale_y_continuous(
        sec.axis = sec_axis(trans = ~./tot_obs, labels = percent, 
                            name = "proportion (in %)")) +
      ylab("count") +
      guides(fill = FALSE)
    #> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
    

    于2018-08-16由 reprex package

    推荐文章