使用2个数组创建直方图

时间:2018-02-10 04:54:52

标签: r histogram

如何在R?

中创建包含此数据的直方图
f = c('0-5', '6-10', '11-15', '16-20', '> 20')
counts_arr = c(0, 8, 129, 127, 173)

目前,counts_arr[0]f[0]

相关联

所以我想让f置于X轴上,counts_arr值置于Y轴上

2 个答案:

答案 0 :(得分:4)

barplot(counts_arr, names = f)

答案 1 :(得分:2)

已经有了一个解决方案,但我准备了ggplot2的东西,但我仍在发布。

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.4.3
library(forcats)
#> Warning: package 'forcats' was built under R version 3.4.3

# dataframe provided
df <-
  base::cbind.data.frame(
    f = c('0-5', '6-10', '11-15', '16-20', '> 20'),
    counts_arr = c(0, 8, 129, 127, 173)
  )

# plot
ggplot2::ggplot(data = df, mapping = aes(x = forcats::fct_inorder(f), y = counts_arr)) +
  geom_bar(stat = "identity") +
  labs(x = "f", y = "count")

reprex package创建于2018-02-10(v0.1.1.9000)。