2012-07-25 202 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