【问题标题】:Plot text/labels centered on a dodged bar plot以闪避的条形图为中心绘制文本/标签
【发布时间】:2017-06-29 07:05:50
【问题描述】:

我不知道如何在ggplot2 的条形图中以每个闪避条为中心显示标签。

我知道我可以使用position = "dodge" 避开​​条形图,并且我知道为了使标签显示在每个条形图的中心,我需要在geom_text()geom_label() 命令中添加position = position_dodge(width = 1)

但由于某种原因它不起作用(见下图)。我还添加了我的数据和代码。

df <- structure(list(Measure = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1988", 
"2017"), class = "factor"), Province = structure(c(1L, 2L, 3L, 
4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 
9L, 10L), .Label = c("BC", "AB", "SK", "MB", "ON", "QC", "NB", 
"PE", "NS", "NL"), class = "factor"), Value = c(363L, 61L, NA, 
69L, NA, NA, 127L, 12L, 92L, 18L, 178L, 29L, 41L, 92L, 284L, 
1019L, 267L, 27L, 77L, 22L)), .Names = c("Measure", "Province", 
"Value"), row.names = 41:60, class = "data.frame")

ggplot(df, aes(x=Province, y=Value)) + geom_bar(aes(fill=Measure), position="dodge", 
stat="identity") + geom_label(aes(label=Value), position = position_dodge(width=1))

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    我刚刚意识到(感谢@aelwan 的回答)我唯一需要做的就是在aes() 函数中添加group=Measure,即

    ggplot(df, aes(x=Province, y=Value, group=Measure)) +
           geom_bar(aes(fill=Measure),position="dodge", stat="identity") + 
           geom_label(aes(label=Value),position = position_dodge(width=1))
    

    这给了:

    【讨论】:

      【解决方案2】:

      试试这个

      ggplot(df, aes(x=Province, y=Value, group = Measure)) + 
        geom_col(aes(fill=Measure), 
                 position ="dodge", width = 0.4)+
        geom_text(aes(label= Value,
                      group = Measure
        ),vjust= 0,  position = position_dodge(0.4) , color="black" )
      

      【讨论】:

      • 感谢您的回答!您的方法也有效,但当我看到您的代码时,我意识到我只需要添加 group=Measure 就可以了。
      【解决方案3】:

      这是一个迟到的答案,但 geom_text 并没有完全居中在条形之上。解决此问题的一种方法是同时指定条形的宽度position=position_dodge(width = 1)

      geom_bar(aes(fill=Measure),position=position_dodge(width = 1), stat="identity")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-25
        • 2023-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多