【问题标题】:adding both count and proportion to histogram in ggplot2 using dual y-axes使用双 y 轴将计数和比例添加到 ggplot2 中的直方图
【发布时间】:2018-08-16 22:09:28
【问题描述】:

我正在尝试创建一个直方图,其中在 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 函数中使用的转换函数不正确。但我不知道有任何其他方法可以做到这一点。将不胜感激提供的任何帮助。

【问题讨论】:

    标签: r ggplot2 histogram tidyverse


    【解决方案1】:

    因为每个条形高度都将除以相同的数字,您可以预先计算分母(下面的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`.
    

    reprex package (v0.2.0) 于 2018 年 8 月 16 日创建。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-20
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多