r - ggplot2 在直方图中查找计数最大值

标签 r ggplot2

我有一个简短的 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))

最佳答案

例如使用的数据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))

enter image description here

关于r - ggplot2 在直方图中查找计数最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14584093/

相关文章:

r - ggplot中的条形图

使用 ggplot2 在美国专题 map 上重新定位阿拉斯加和夏威夷

r - 如何获得 R 中各列的唯一 ID 计数?

r - Predict() 函数的奇怪行为

r - R-Studio 版本 0.98.953 - 启动时控制台中出现错误消息

r - 使用ggplot2创建一个facet_wrap图,每个图中都有不同的注释

r - 在ggplot中设置注释文本的宽度

javascript - 解析一个 JSON 字符串并显示它

r - 四开展示幻灯片 : text color for a single slide

r - 将图像插入图表区域外的 ggplot