在ggplot2中创建计数频率的直方图

时间:2016-04-12 19:04:47

标签: r ggplot2 histogram

假设我有以下数据框:

d = data.frame(letter = c(
    'a', 'a', 'a', 
    'b', 'b', 'b', 
    'c',
    'd', 'd', 'd', 'd',
    'e', 'e', 
    'f', 'f', 'f', 'f', 'f', 'f', 'f',
    'g'))

如何使用ggplot2制作直方图,该直方图不计算给定字母出现的次数,而是计算给定字母频率出现的次数?在这个例子中:

table(d$letter)

a b c d e f g 
3 3 1 4 2 7 1 

两个字母(c和g)出现一次,一个字母(e)出现两次,两个字母出现三次,等等。这样你就可以制作一个等同于基础图的数字:

hist(table(d$letter), right = F, breaks = 6)

base histogram

1 个答案:

答案 0 :(得分:2)

您可以将table的结果转换为数据框,然后使用ggplot

df <- as.data.frame(table(d$letter))
ggplot(df, aes(x = Freq)) +
    geom_histogram(binwidth = 1)

enter image description here

这是有效的,因为包含频率的列默认称为Freq

head(df)
##   Var1 Freq
## 1    a    3
## 2    b    3
## 3    c    1
## 4    d    4
## 5    e    2
## 6    f    7

如果要让条形位于整数之间,可以使用center = 0.5将区间中心设置为半整数。我还使用closed = "left",相当于right = FALSE中的hist()

ggplot(df, aes(x = Freq)) +
  geom_histogram(binwidth = 1, center = 0.5, closed = "left") +
  scale_x_continuous(breaks = 1:7)

enter image description here

相关问题