2012-07-25 200 views
24

我想用条形图内的百分比来做一个黑色条形图。这可能来自qplot吗?我得到的百分比出现,但他们不符合特定的酒吧。将标签添加到ggplot条形图

包: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

欢迎到SO。由于您使用的是非基本的R函数,因此请添加对重现代码所需的包的引用,即'library(...)' – Andrie 2012-07-25 15:32:28

回答

41

在这里你去:

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

+0

感谢您的geom_text部分。你能解释ymax变量推理吗? – 2012-07-25 16:10:03

+0

哦,对不起 - 它可能是多余的。我不得不用一些奇怪的警告来争取一点点。尝试删除它,看看会发生什么。 – Andrie 2012-07-25 16:51:17

+1

只是想要注意'percent_format()需要'library(scales)' – dudusan 2014-10-21 04:56:35

4

这将是一个很好的机会,让你开始使用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()) 

对于哲学的原因,我将注释一块留给你......

+0

谢谢。情节中仍然没有文字/百分比。我是否将'值'传递给percent_format()? – 2012-07-25 15:54:57

+1

@RoundBound我知道。我故意省略文本标签,因为我在哲学上反对以这种方式标记条形图。 (但是如果你想制作标签,你不会在'scale_y_continuous'中使用任何东西。) – joran 2012-07-25 15:58:12

+1

我明白了。你个人喜欢什么?我该如何添加文本?非常感谢您的帮助。 – 2012-07-25 16:02:21