簡體   English   中英

在基礎 R 的條形圖頂部添加計數標簽

[英]Add Count Labels on Top of Barchart in base R

我有一個條形圖,我希望在每個條形頂部添加計數標簽。 有人可以告訴我如何在基礎 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")

制作 plot

counts <- table(df$TargetBuy)

在這里您需要更改 y 軸刻度,因為如果您不這樣做,頂部 label 將不會顯示

b <- barplot(counts, main= "number of yes/no", xlab = "response", ylab = "number of occurrences", ylim=c(0,4))

要添加標簽,您需要將text()添加到 plot

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")

這會產生一個看起來像這樣的 plot。 請注意,我將 y 軸長度更改為 4。如果將其設置為 3,則第一個欄上方的頂部 3 將不會顯示

示例1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM