我有一个简短的[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))
就个人而言,我觉得“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”功能,所以我更喜欢直接调用它的时候,我只想要的数据。