在 base R 中的条形图顶部添加计数标签
Add Count Labels on Top of Barchart in base R
我有一个条形图,我希望在每个条形图的顶部添加计数标签。有人能告诉我如何在 base R 中做到这一点而不使用 ggplot2 吗?
自从我看到你的最后一个 我比其他人更详细。
示例数据
structure(list(ID = c(140L, 620L, 868L, 1120L, 2313L), DemAffl = c(10L,
4L, 5L, 10L, 11L), DemAge = c(76L, 49L, 70L, 65L, 68L), DemCluster = c(16L,
35L, 27L, 51L, 4L), DemClusterGroup = c("C", "D", "D", "F", "A"
), DemGender = c("U", "U", "F", "M", "F"), DemReg = c("Midlands",
"Midlands", "Midlands", "Midlands", "Midlands"), DemTVReg = c("Wales & West",
"Wales & West", "Wales & West", "Midlands", "Midlands"), PromClass = c("Gold",
"Gold", "Silver", "Tin", "Tin"), PromSpend = c(16000, 6000, 0.02,
0.01, 0.01), PromTime = c(4L, 5L, 8L, 7L, 8L), TargetBuy = c(0L,
0L, 1L, 1L, 0L), TargetAmt = c(0L, 0L, 1L, 1L, 0L)), row.names = c(NA,
5L), class = "data.frame")
制作剧情
counts <- table(df$TargetBuy)
此处您需要更改 y 轴刻度,否则顶部标签将不会显示
b <- barplot(counts, main= "number of yes/no", xlab = "response", ylab = "number of occurrences", ylim=c(0,4))
要添加标签,您需要将 text()
添加到图
text(x= b, y=counts,pos = 3, label = counts, cex = 0.8, col = "red")
所以完整的东西看起来像这样
counts <- table(df$TargetBuy)
b <- barplot(counts, main= "number of yes/no", xlab = "response", ylab = "number of occurrences", ylim=c(0,4)
text(x= b, y=counts,pos = 3, label = counts, cex = 0.8, col = "red")
这会生成如下图。注意我把y轴长度改成了4,如果设置成3,第一个bar上面的top 3就不会显示了
我有一个条形图,我希望在每个条形图的顶部添加计数标签。有人能告诉我如何在 base R 中做到这一点而不使用 ggplot2 吗?
自从我看到你的最后一个
示例数据
structure(list(ID = c(140L, 620L, 868L, 1120L, 2313L), DemAffl = c(10L,
4L, 5L, 10L, 11L), DemAge = c(76L, 49L, 70L, 65L, 68L), DemCluster = c(16L,
35L, 27L, 51L, 4L), DemClusterGroup = c("C", "D", "D", "F", "A"
), DemGender = c("U", "U", "F", "M", "F"), DemReg = c("Midlands",
"Midlands", "Midlands", "Midlands", "Midlands"), DemTVReg = c("Wales & West",
"Wales & West", "Wales & West", "Midlands", "Midlands"), PromClass = c("Gold",
"Gold", "Silver", "Tin", "Tin"), PromSpend = c(16000, 6000, 0.02,
0.01, 0.01), PromTime = c(4L, 5L, 8L, 7L, 8L), TargetBuy = c(0L,
0L, 1L, 1L, 0L), TargetAmt = c(0L, 0L, 1L, 1L, 0L)), row.names = c(NA,
5L), class = "data.frame")
制作剧情
counts <- table(df$TargetBuy)
此处您需要更改 y 轴刻度,否则顶部标签将不会显示
b <- barplot(counts, main= "number of yes/no", xlab = "response", ylab = "number of occurrences", ylim=c(0,4))
要添加标签,您需要将 text()
添加到图
text(x= b, y=counts,pos = 3, label = counts, cex = 0.8, col = "red")
所以完整的东西看起来像这样
counts <- table(df$TargetBuy)
b <- barplot(counts, main= "number of yes/no", xlab = "response", ylab = "number of occurrences", ylim=c(0,4)
text(x= b, y=counts,pos = 3, label = counts, cex = 0.8, col = "red")
这会生成如下图。注意我把y轴长度改成了4,如果设置成3,第一个bar上面的top 3就不会显示了