【问题标题】:Relative frequency histogram in R, ggplotR中的相对频率直方图,ggplot
【发布时间】:2019-12-17 05:52:01
【问题描述】:

我可以在R中绘制相对频率直方图,使用lattice包:

a <- runif(100)
library(lattice)
histogram(a)

我想在ggplot 中获得相同的图表。我试过了

dt <- data.frame(a)
ggplot(dt, aes(x = a)) + 
geom_bar(aes(y = ..prop..))+
 scale_y_continuous(labels=percent)

但它不是那样工作的。我应该在代码中更改什么?在图表之前计算相对频率对我来说不是一个选项。

【问题讨论】:

  • 我猜你在找geom_histogram
  • ggplot(dt, aes(x=a)) + geom_histogram()
  • 不,我需要相对频率,而不是计数。

标签: r ggplot2 plot frequency lattice


【解决方案1】:

你可以试试:

ggplot(data=df, aes(x=a)) + geom_bar(aes(y = (..count..)/sum(..count..)), group = 1)

【讨论】:

  • 不,用这种方法我只能看到三个垂直线,而不是分布。
  • 这应该等同于使用..prop..
【解决方案2】:

你想要一个直方图,而不是条形图,所以:

ggplot(dt, aes(x = a)) + 
  geom_histogram(aes(y = stat(count) / sum(count)), bins = 8) +
  scale_y_continuous(labels = scales::percent)

lattice:

ggplot2:

您可以看到分箱算法对两个包的工作方式略有不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-11
    • 2013-06-29
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    相关资源
    最近更新 更多