【问题标题】:Adding COUNT in barplot in R在 R 中的条形图中添加 COUNT
【发布时间】:2020-01-09 14:24:24
【问题描述】:

我是 R 的初学者。我在将计数放入条形图中时遇到问题。

所以我的数据看起来像这样

> head(worker)
  stateur statemb state age tenure    joblost
1     4.5     167    42  49     21      other
2    10.5     251    55  26      2 slack_work
3     7.2     260    21  40     19      other
4      NA     245    56  51     17 slack_work
5     6.5     125    58  33      1 slack_work
6     7.5     188    11  51      3      other

我已经使用此代码绘制了条形图

table=table(worker$joblost)
barplot(table, main = "Vertical Bar Plot of the Job Lost")

但我想将每个类别的失业频率放在每个条形的顶部。我能做什么?

【问题讨论】:

    标签: r bar-chart


    【解决方案1】:

    使用text()barplot() 有一个不可见的输出,您可以使用<- 捕获它,并将其用于要添加的文本的x 位置。对于y=,只需添加表值以及看起来不错的内容。

    b <- barplot(tab, beside=TRUE, ylim=c(0, max(tab) + 15), 
                 main="Vertical Bar Plot of the Job Lost", col=2:3, border=0)
    text(b, tab + 5, tab, font=2, col=2:3)
    

    注意,通过使用"table" 作为对象的名称,您会尝试覆盖table() 函数!务必事先检查名称是否免费,输入?table。如果没有,请使用其他东西。


    数据:

    tab <- structure(c(other = 56L, slack_work = 44L), .Dim = 2L, .Dimnames = structure(list(
        c("other", "slack_work")), .Names = ""), class = "table")
    

    【讨论】:

    • 谢谢先生!!你的回答对我这样的初学者真的很有帮助。
    【解决方案2】:

    您可以使用以下代码

    library(ggplot2)
    
      ggplot(worker,aes(x=factor(joblost)))+
      geom_bar(position="dodge")+ 
      labs(title="Vertical Bar Plot of the Job Lost", x="Job lost", y = "Frequency")+
      geom_text(aes(label=..count..),stat='count',position=position_dodge(0.9),vjust=-0.2)
    

    【讨论】:

    • 鉴于 Izzah 是 R 新手,您应该指定您的解决方案涉及使用 ggplot2 而不是基本 R 的绘图,并且您需要从 library(ggplot2) 开始。
    • 非常感谢先生!!但不幸的是,我仍然不熟悉使用其他 R 包。稍后我将探索该软件包并尝试使用您的方法。
    • @lzzah 在运行代码之前只需使用一次install.packages("ggplot2")。它将安装ggplot2 包,下次您只需通过library(ggplot2) 调用包。
    猜你喜欢
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多