[英]How to put labels over geom_bar for each bar in R with ggplot2
我發現了這個, 如何使用 ggplot2 將標簽放在 R 中的 geom_bar 上,但它只是將標簽(數字)放在一個條上。
這是,讓我們說,每個 x 軸有兩個條形,如何做同樣的事情?
我的數據和代碼如下所示:
dat <- read.table(text = "sample Types Number
sample1 A 3641
sample2 A 3119
sample1 B 15815
sample2 B 12334
sample1 C 2706
sample2 C 3147", header=TRUE)
library(ggplot2)
bar <- ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = 'dodge') + geom_text(aes(label=Number))
然后,我們會得到:
似乎數字文本也定位在“躲避”模式中。 我搜索了geom_text 手冊以找到一些信息,但無法使其工作。
建議?
嘗試這個:
ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = 'dodge', stat='identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)
要添加到 rcs 的答案中,如果您想在 x 是 POSIX.ct 日期時將 position_dodge() 與 geom_bar() 一起使用,則必須將寬度乘以 86400,例如,
ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = "dodge", stat = 'identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.