R图形: add labels to clustered/dodged bar chart

标签 r plot bar-chart

这是一个基本的绘图问题:

我需要向聚集/闪避条形图添加标签。我已经查看了几个使用 text() 的示例,但似乎无法正确定位标签。

teachers <- c("A", "B","C", "D", "E")
mean_pre_scores <- c(10, 11, 12, 10,9)
mean_post_scores <- c(12,15,17,13,12)
pre_post <- data.frame(mean_pre_scores, mean_post_scores)

pre_post <- as.matrix(pre_post)
barplot((t(pre_post)), beside = T, names = teachers, legend = c("pre", "post"), 
        ylim = c(0,20), args.legend = list(x="bottomright"),  axes = T, main = "Unit 1 Test",
        col=c(26,51))

我想修改此图,以便值将显示在条形上方。了解如何显示条形内的值也会很有帮助。

最佳答案

我认为这就是您所追求的:

z <- barplot((t(pre_post)), beside = T, names = teachers, 
    legend = c("pre", "post"), ylim = c(0,20), 
    args.legend = list(x="topright"),  axes = T, 
    main = "Unit 1 Content Pre Test", col=c(26,51))

text(cex=1, x=c(z[1, ], z[2, ]), y=c(pre_post) + par("cxy")[2]/2, c(pre_post), xpd=TRUE) 

enter image description here

要在条内移动文本,只需使用减法,如下所示:

text(cex=1, x=c(z[1, ], z[2, ]), y=c(pre_post) - par("cxy")[2]/2, c(pre_post), xpd=TRUE) 

关于R图形: add labels to clustered/dodged bar chart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23294528/

相关文章:

python - 在 Plotly 的 Scattergeo 图中制作图例

r - ggplot2 和 geom_密度 : How to remove baseline?

python - 条形图 xtick 标签的位置有不规则的空间

R神经网络: "non-conformable arguments"

r - 将自定义函数与 tidyverse 结合使用

r - 我陷入了 R 数据编程中的 FOR 和 IF 函数任务

javascript - 当显示 10 个以上系列时,Highcharts 列会变薄

r - 为什么 write.csv 和 read.csv 不一致?

python pandas 重新索引删除 0.0 处的数据

r - R ggplot2 中比例的堆叠条形图按两个因素的水平分组