简体   繁体   中英

Plot distribution using ggplot2

I am working with the language R to generate average samples follow a normal distribution. The distribution of the variable X is not showing in the chart. I am getting a blank chart in my R plots. I used the following code:

set.seed(1)
d = data.frame(X=rbeta(20000,2,5))
p = ggplot(d, aes(x=X))
p + geom_bar(aes(y=(..count..)/sum(..count..))) + ylab("Frequency Percent")

Am I missing something?

Use geom_histogram for continuous data:

?geom_histogram

Display a 1d distribution by dividing into bins and counting the number of observations in each bin. ...

R> p <- ggplot(d, aes(x=X))
R> p + geom_histogram(aes(y=(..count..)/sum(..count..))) +
   ylab("Frequency Percent") 

情节

geom_histogram uses stat_bin by default, which bins data in ranges and counts the cases in each range. It differs from stat_count (default stat for geom_bar ), which counts the number of cases at each x position (without binning into ranges). stat_bin requires continuous x data, whereas stat_count can be used for both discrete and continuous x data.

You are missing stat = "bin"

set.seed(1)
d = data.frame(X=rbeta(2000,2,5))
p = ggplot(d,aes(x=X))
p + geom_bar(aes(y=(..count..)/sum(..count..)), stat="bin") +
    ylab("Frequency Percent")

This SO answer is helpful here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM