Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

r - Adding labels to ggplot bar chart

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...