【问题标题】:How do I get units (NOT label) to be displayed on the X axis of a barplot?如何让单位(非标签)显示在条形图的 X 轴上?
【发布时间】:2020-03-31 16:56:46
【问题描述】:

我正在尝试创建一个数据可视化来显示按班级数量划分的学校数量。我创建了一个这样做的小标题(我已粘贴在下面)其中有两列,“c(grade5$schlcode)”显示唯一学校代码的列表,“n”是每所学校内的班级数量代码。

n_classes <- count(grade5, c(grade5$schlcode))
> 
> n_classes
# A tibble: 1,002 x 2
   `c(grade5$schlcode)`     n
                  <dbl> <int>
 1                11005     2
 2                11006     2
 3                11009     1
 4                11010     2
 5                11013     3
 6                11015     3
 7                11017     2
 8                11020     3
 9                11021     2
10                11027     3
# … with 992 more rows

然后我统计了学校的数量,以便创建一个tibble 来制作这个barplot

> x <- count(n_classes, c(n_classes$n))
> x
# A tibble: 6 x 2
  `c(n_classes$n)`     n
             <int> <int>
1                1   296
2                2   456
3                3   199
4                4    42
5                5     8
6                6     1

但是当我制作图时,它正确显示了有 1 个班级和 2 个班级和 3 个班级等等的学校的频率,但我没有显示 X 轴的单位(所以每个条形图应该标记为 1、2 , 3, 4 (classes)。但是没有单元只有 xlab!

> barplot(x$n, x$`c(n_classes$n)`,
+         xlab = "Number of Classes in a School",
+         ylab = "Frequency of Schools",
+         main = "Number of Classes Schools Have",
+         col = "grey",
+         border = "orange")

我该如何解决这个问题?

【问题讨论】:

  • 通常的约定是将单位放在xlabylab 中,例如“一所学校的班级数(计数)”。如果你想把“(count)”放在别的地方,你可能需要使用mtext() 明确地把它放在那里。

标签: r bar-chart units-of-measurement


【解决方案1】:

你有一个非常奇怪的计数列名,这会导致很多问题:

x = data.frame("`c(n_classes$n)`" = 1:6,
n=c(296,456,199,42,8,1),check.names=FALSE)

如果我们这样做,

x$`c(n_classes$n)`
NULL

这是因为它将 ` 解释为字符串。你可以试试:

barplot(x$n,x$"`c(n_classes$n)`",
         xlab = "Number of Classes in a School",
         ylab = "Frequency of Schools",
         main = "Number of Classes Schools Have",
         col = "grey",
         border = "orange")

所有这些都可以通过在向量上调用 table 两次来避免:

set.seed(100)
grade5 = data.frame(schlcode=sample(1:20,100,replace=TRUE))
barplot(table(table(grade5$schlcode)))

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 2021-12-03
    • 1970-01-01
    • 2019-01-28
    • 2017-09-26
    • 1970-01-01
    • 2021-07-24
    • 2021-03-18
    • 2019-07-15
    相关资源
    最近更新 更多