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"
With the normal plot command that works. I want to replicate this command in 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.
To add labels on top of each bar in Barplot in R we use the geom_text() function of the ggplot2 package. Parameters: value: value field of which labels have to display. nudge_y: distance shift in the vertical direction for the label.
There are two types of bar charts: geom_bar() and geom_col() . geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col() instead.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With