如何为一个变量创建直方图,使用另一个变量确定其频率?

时间:2015-08-30 19:17:35

标签: r histogram

我是R的新手,并且是第一次使用直方图。我需要构建一个直方图,以显示所有50个美国+哥伦比亚特区的收入频率。

这是给我的数据:

> data
  X.Income. X.No.States.
1   -22.024            5
2   -25.027           13
3   -28.030           16
4   -31.033            9
5   -34.036            4
6   -37.039            2
7   -40.042            2
> hist(data$X.Income, col="red")

但是,这仅产生每个收入金额出现在图表中的频率数量的直方图,而不是具有该收入水平的州的数量。如何计算图表中每个收入水平的州数? Look at my histogram here

1 个答案:

答案 0 :(得分:1)

使用条形图而不是直方图,因为直方图需要为您计算频率:

library(ggplot2)

# make some data to exercise
income = c(-22.024, -25.027, -28.030, -31.033, -34.036, -37.039,-40.042)
freq = c(5,13,16,9,4,2,2)
df <- data.frame(income, freq)
df <- names(c("income","freq"))

# the graph object
p <- ggplot(data=df) +
   aes(x=income, y=freq) +
   geom_bar(stat="identity", fill="red")

# call the object to view
p