Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

r - ggplot2 find number of counts in histogram maximum

I have a short R script which plots a few histograms using ggplot2. How can I automatically set the ymax limit in the histogram based on the maximum frequency in the histogram (plus 10%) i.e

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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For example used data movies as sample data are not provided.

With function ggplot_build() you can get list containing all the elements used for plotting your data. All the data are in list element data[[1]]. Column count of this element contains values for histogram. You can use maximal value of this column to set limits for your plot.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...