【问题标题】:R graphics: Add labels to stacked bar chartR图形:为堆积条形图添加标签
【发布时间】:2011-04-07 06:44:20
【问题描述】:

我正在寻找一种使用 R 的基本绘图功能将标签(即绝对值)添加到堆叠条形图中的方法。标签应该在堆叠条内。

谢谢!

【问题讨论】:

    标签: r label bar-chart stacked


    【解决方案1】:

    barplot 将返回条形的中间 x 位置,所以你可以这样做

    mydata <- matrix(c(10, 21, 22, 33, 45, 23, 22, 43, 33), nrow=3)
    
    # b will contain the x midpoints of the bars
    b <- barplot(mydata)
    
    # This will write labels in the middle of the bars, horizontally and vertically
    text(b, colMeans(mydata), c("Label1", "Label2", "Label3"))
    
    # This will write labels in the middle of the middle block
    text(b, mydata[1,]+mydata[2,]/2, c("LabelA", "LabelB", "LabelC"))
    

    编辑:重新阅读您的问题,我认为这是您想要的(或者可能不是,但我还是会写它:D)

    # Find the top y position of each block 
    ypos <- apply(mydata, 2, cumsum)
    # Move it downwards half the size of each block
    ypos <- ypos - mydata/2
    ypos <- t(ypos)
    
    text(b, ypos, mydata)
    

    【讨论】:

    • 嗨 Nico,哇,这与垂直条形图完美配合。非常感谢。我很高兴解决方案不是那么神秘。我也尝试将您的代码应用于垂直条形图。简单地交换 b 和 ypos 就可以了。非常感谢!
    【解决方案2】:

    简单的函数text()怎么样?

    你可以简单地在任何你想要的地方添加一个字符串,例如:

    text (x = ..., y = ..., labels = c("foo bar 1000"))
    

    【讨论】:

    • text 也是我的首选,但我如何告诉 R 它应该将我的数据集中的值放在堆栈本身的中心?
    【解决方案3】:

    也许你可以使用或检查plotrix包的barp函数

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 2013-12-22
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 2017-11-27
      • 2016-10-11
      相关资源
      最近更新 更多