I'm trying to plot a labeled barplot with ggplot2 with positive and negative bars. That works so far, but I would like to set the label outside of the bar, so that it is above or under the bar. I tried to set an adjustment in vjust = c(x1,...,xn)
where x
is a positive or negative value according to the value of the bar in geom_text()
. This doesn't work. I just got the Error message Error: "When setting aesthetics, they may only take one value. Problems: vjust"
我正在尝试使用带有正负条的ggplot2绘制标记的条形图。到目前为止,这是有效的,但我想在标签之外设置标签,使其位于条形图的上方或下方。我试图在vjust = c(x1,...,xn)中设置一个调整,其中x是一个正值或负值,根据geom_text()中的bar值。这不起作用。我刚收到错误消息错误:“设置美学时,它们可能只取一个值。问题:vjust”
With the normal plot command that works. I want to replicate this command in ggplot2:
使用正常的plot命令。我想在ggplot2中复制这个命令:
xpos <- barplot(d, col=mycols, main='Verteilung in Dresden 2004',
ylab='Anteil in %', xlab='Milieu', names.arg=l,
cex.axis=0.7, cex.names=0.7, ylim=c(0,max(d)+0.05))
boxed.labels(xpos,d+0.02,sprintf('%d%s', d*100, '%'),
bg='transparent', border=FALSE, cex=0.7)
So that it looks like this just in nice... ;-)
所以它看起来很好...... ;-)
Does someone have any suggestions?
有人有什么建议吗?
Thank's for y'all help.
谢谢你的帮助。
1 个解决方案
#1
37
This does the trick
这样就可以了
library(plyr)
library(ggplot2)
library(scales)
dtf <- data.frame(x = c("ETB", "PMA", "PER", "KON", "TRA",
"DDR", "BUM", "MAT", "HED", "EXP"),
y = c(.02, .11, -.01, -.03, -.03, .02, .1, -.01, -.02, 0.06))
ggplot(dtf, aes(x, y)) +
geom_bar(stat = "identity", aes(fill = x), legend = FALSE) +
geom_text(aes(label = paste(y * 100, "%"),
vjust = ifelse(y >= 0, 0, 1))) +
scale_y_continuous("Anteil in Prozent", labels = percent_format()) +
opts(axis.title.x = theme_blank())
#1
37
This does the trick
这样就可以了
library(plyr)
library(ggplot2)
library(scales)
dtf <- data.frame(x = c("ETB", "PMA", "PER", "KON", "TRA",
"DDR", "BUM", "MAT", "HED", "EXP"),
y = c(.02, .11, -.01, -.03, -.03, .02, .1, -.01, -.02, 0.06))
ggplot(dtf, aes(x, y)) +
geom_bar(stat = "identity", aes(fill = x), legend = FALSE) +
geom_text(aes(label = paste(y * 100, "%"),
vjust = ifelse(y >= 0, 0, 1))) +
scale_y_continuous("Anteil in Prozent", labels = percent_format()) +
opts(axis.title.x = theme_blank())