【问题标题】:Adding values to barplot of table in R将值添加到 R 中表格的条形图
【发布时间】:2014-12-14 03:26:52
【问题描述】:

我正在尝试使用 barplot 绘制一个表格并为其添加值。

tt = structure(c(7L, 13L, 24L, 30L, 30L, 38L, 35L, 45L, 37L, 
43L, 38L, 59L, 33L, 45L, 37L, 58L), .Dim = c(2L, 8L), .Dimnames = structure(list(param = c("A", 
"B"), xvar = c("5", "6", "7", "8", "9", "10", "11", "12")), .Names = c("param", "xvar")), class = "table")
tt
     xvar
param  5  6  7  8  9 10 11 12
    A  7 24 30 35 37 38 33 37
    B 13 30 38 45 43 59 45 58

bb= barplot(tt)
text(bb, 0, tt)

还有:

bb= barplot(tt)
text(bb, tt, tt)

两者都没有正确放置值。我也在 text() 中尝试了 t(tt) 但它不能正常工作。如何才能做到这一点。感谢您的帮助。

【问题讨论】:

    标签: r bar-chart


    【解决方案1】:

    嗯,这行得通,但我不得不认为有更好的方法......

    bb <- barplot(tt, col=c("grey60","grey80"))
    text(bb,tt[1,]-4,labels=tt[1,],cex=.8)
    text(bb,colSums(tt)-4,labels=tt[2,],cex=0.8)
    

    这是一个ggplot 解决方案,只是为了完整性。

    library(ggplot2)
    ggplot(as.data.frame(tt),aes(x=factor(xvar),y=Freq,fill=param)) +
      geom_bar(stat="identity",position="stack")+
      geom_text(aes(label=Freq),position="stack",vjust=1)+
      scale_fill_manual(values=c("grey60","grey80"))+
      theme_bw()
    

    【讨论】:

    • 我特别喜欢 ggplot 版本。谢谢。
    • 请您帮忙订购上图中的条形图,所有标签保持原样。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 2017-07-29
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    相关资源
    最近更新 更多