向ggplot条形图添加标签

时间:2012-07-25 15:29:12

标签: r ggplot2

我想做一个黑色轮廓的条形图,条形图内有百分比。这可能来自qplot吗?我得到百分比,但它们与特定的条形图不对齐。

包:ggplot2,重塑

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)

2 个答案:

答案 0 :(得分:45)

你走了:

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

答案 1 :(得分:5)

这将是您开始不再使用qplot的好机会,而是ggplot。从长远来看,这将更容易,相信我。

这是一个开始:

library(scales)
ggplot(data = x,aes(x = factor(filename),y = value)) + 
    geom_bar(aes(fill = factor(variable)),colour = "black",position = 'dodge') + 
    coord_flip() + 
    scale_fill_manual(name = '',
                      labels = c('low',
                                 'Hi',
                                 "Tot"),
                      values = c('#40E0D0',
                                 '#FF6347',
                                 "#C7C7C7")) + 
    scale_y_continuous(labels = percent_format())

出于哲学原因,我会把注释片留给你......