【问题标题】:Histogram with count R计数为 R 的直方图
【发布时间】:2019-01-16 15:58:00
【问题描述】:

我正在尝试创建我的数据的直方图。 我的数据框看起来像这样

x  counts
4  78
5  45
... ...

其中 x 是我想要绘制的变量,counts 是观察次数。如果我做 hist(x) 情节将是误导,因为我没有考虑计数。我也试过:

hist(do.call("c", (mapply(rep, df$x, df$count))))

不幸的是,这不起作用,因为结果向量太大

sum(df$ount)
[1] 7943571126

我还有其他方法可以尝试吗?

谢谢

【问题讨论】:

  • 可能是barplot
  • x 是一个连续变量,如何绘制条形图?
  • 我的意思是计数的条形图。您发布的数据不显示连续变量。
  • @MarcoDeVirgilis 这些解决方案是否解决了您的问题?如果您找到其他解决方案,请随意添加您自己的答案,或接受答案。

标签: r count bigdata histogram frequency


【解决方案1】:

解决方案是 @Rui Barradas 建议的条形图。我使用ggplot 绘制数据。

library(ggplot2)
x <- c(4, 5, 6, 7, 8, 9, 10)
counts <- c(78, 45, 50, 12, 30, 50)
df <- data.frame(x=x, counts=counts)

plt <- ggplot(df) + geom_bar(aes(x=x, y=counts), stat="identity")
print(plt)

【讨论】:

  • 可以简化为geom_col(aes(x=x, y=counts))
【解决方案2】:

由于数据的大小,不可能为 x 的每个重复创建一个新行,因此您可以使用 ggplot2 中的 weightgeom_histogram 绘制密度。

library(tidyverse)
set.seed(1)
x <- 1:100
counts <- sample(20:200,100,T)
df <- data.frame(x,counts)

df %>% ggplot() +geom_histogram(aes(x=x, y=..density..,weight=counts))

将此与仅绘制计数进行比较:

df %>% ggplot() +geom_histogram(aes(x=x))

【讨论】:

    猜你喜欢
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2013-07-24
    • 1970-01-01
    • 2020-08-08
    • 2011-09-17
    • 1970-01-01
    相关资源
    最近更新 更多