Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding labels to ggplot bar chart

Tags:

r

ggplot2

I would like to do a bar plot outlined in black with percentages inside the bars. Is this possible from qplot? I get the percentages to appear but they don't align with the particular bars.

packages: ggplot2, reshape

created in Illustrator

x <- data.frame(filename = c("file1", "file2", "file3", "file4"),                     low = c(-.05,.06,.07,-.14),                     hi = c(.87,.98,.56,.79)) x$tot <- x$hi + x$low  x <- melt(x, id = 'filename')  bar <- qplot(x = factor(filename),               y = value*100,              fill = factor(variable),              data = x,              geom = 'bar',              position = 'dodge') + coord_flip() bar <- bar + scale_fill_manual(name = '',                                labels = c('low',                                           'Hi',                                           "Tot"),                                values = c('#40E0D0',                                           '#FF6347',                                           "#C7C7C7"))  bar <- bar + geom_text(aes(label = value*100))+geom_bar(colour = 'black') bar <- bar + opts(panel.background = theme_rect(colour = NA)) bar <- bar + opts(legend.justification = 'bottom') print(bar) 
like image 572
Michael Street Avatar asked Jul 25 '12 15:07

Michael Street


People also ask

How do I add labels to a bar chart in R?

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.

How do I change data labels in ggplot2?

Changing axis labels To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .

How do I label a bar graph in Excel?

Add data labelsClick the chart, and then click the Chart Design tab. Click Add Chart Element and select Data Labels, and then select a location for the data label option.

How do I reorder bar charts in R?

To reorder bars manually, you have to pass stat=”identity” in the geom_bar() function.


1 Answers

Here you go:

library(scales) ggplot(x, aes(x = filename, fill = variable)) +   geom_bar(stat="identity", ymin=0, aes(y=value, ymax=value), position="dodge") +   geom_text(aes(x=filename, y=value, ymax=value, label=value,                  hjust=ifelse(sign(value)>0, 1, 0)),              position = position_dodge(width=1)) +   scale_y_continuous(labels = percent_format()) +   coord_flip() 

enter image description here

like image 136
Andrie Avatar answered Sep 28 '22 09:09

Andrie