【问题标题】:ggplot2 find number of counts in histogram maximumggplot2 查找直方图中的计数最大值
【发布时间】:2013-01-13 02:14:42
【问题描述】:

我有一个简短的 R 脚本,它使用 ggplot2 绘制了一些直方图。如何根据直方图中的最大频率(加 10%)自动设置直方图中的 ymax 限制,即

scale_y_continuous(limits= c(0,ymax*1.1)

plot = ggplot(data, aes(myo_activity)) +
  geom_histogram(binwidth=0.5, aes(fill=..count..))
plot + scale_x_continuous(expand = c(0,0), limits = c(30,90)) + 
  scale_y_continuous(expand = c(0,0), limits = c(0,140))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    未提供例如使用数据movies作为样本数据。

    使用函数ggplot_build(),您可以获得包含用于绘制数据的所有元素的列表。所有数据都在列表元素data[[1]] 中。此元素的count 列包含直方图的值。您可以使用此列的最大值为您的绘图设置限制。

    plot = ggplot(movies, aes(rating)) + geom_histogram(binwidth=0.5, aes(fill=..count..))
    ggplot_build(plot)$data[[1]]
          fill    y count     x     ndensity       ncount      density PANEL group ymin ymax xmin xmax
    1  #132B43    0     0  0.75 0.0000000000 0.0000000000 0.0000000000     1     1    0    0  0.5  1.0
    2  #142E48  272   272  1.25 0.0323232323 0.0323232323 0.0092535892     1     1    0  272  1.0  1.5
    3  #16314B  454   454  1.75 0.0539512775 0.0539512775 0.0154453290     1     1    0  454  1.5  2.0
    4  #17344F  668   668  2.25 0.0793820559 0.0793820559 0.0227257263     1     1    0  668  2.0  2.5
    5  #1B3A58 1133  1133  2.75 0.1346405229 0.1346405229 0.0385452813     1     1    0 1133  2.5  3.0
    
    plot + scale_y_continuous(expand = c(0,0),
             limits=c(0,max(ggplot_build(plot)$data[[1]]$count)*1.1))
    

    【讨论】:

    • ggplot_build(plot)$data[[1]] 给了我非常不同的输出 - [,1] [1,] List,12
    • @moadeep 请使用示例数据更新您的问题,以便能够重现您的情况。这个情节也是 ggplot2 版本 0.9.3
    • 以上是我从你在答案中输入的命令得到的输出
    • @moadeep 你的ggplot2是什么版本的?
    • 我有一个旧的 ggplot2 版本。感谢您的优雅解决方案
    【解决方案2】:

    就我个人而言,我发现“hist”函数对这类计算最有用。 “hist”功能非常快,可以提供您的频率计数。对于您的情况,您可以执行以下操作:

    max(hist(data$myo_activity, breaks=seq(range_Min, range_Max, by=bin_Width), plot=FALSE)$counts)
    

    range_Min 是理论范围的底部(即 0),range_Max 是理论范围之上的上限。 bin_Width是每个频率计数的值宽度。

    方程应该为您提供指定绘图范围所需的最大值。我相信 'ggplot' 函数无论如何都会调用 'hist' 函数,所以我更喜欢在只想要数据时直接调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2016-08-03
      相关资源
      最近更新 更多