计数R的直方图

时间:2018-08-09 08:54:09

标签: r count bigdata histogram frequency

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

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

其中x是我想绘制的变量,而count是观察数。如果我执行hist(x),则绘图会产生误导,因为我没有考虑计数。我也尝试过:

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

不幸的是,这不起作用,因为生成的向量太大

sum(df$ount)
[1] 7943571126

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

谢谢

2 个答案:

答案 0 :(得分: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)

barplot

答案 1 :(得分:0)

由于由于数据的大小,不可能为x的每个重复创建新行,因此可以使用weightggplot2中用geom_histogram绘制密度。 / p>

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))

enter image description here

通过绘制计数来比较:

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

enter image description here