2014-10-01 92 views
0

我正在使用ggplot和geom_bar圖層。ggplot2使用文本顏色作爲填充的圖例

library(ggplot2) 
library(dplyr) 
library(reshape2) 

dat <- data.frame(
    A = c(1, 1, 0.5), 
    B = c(1.2, 1, 0.6), 
    FF = c("F1", "F2", "F3") 
) %>% 
    mutate(Other = max(A,B)) 
dat.m <- melt(dat) 

我想重現我看到的因素註釋與ggplot默認指南不同。我不希望文字在面板右側的圖例中顯示fill,而是在每個填充顏色的旁邊添加文本,我希望文本被着色並顯示在面板中。

這是默認選項:

ggplot(filter(dat.m, variable != "Other")) + 
    geom_bar(aes(x = variable, y = value, fill=FF), 
      stat="identity") 

enter image description here

這是我做了模仿我的風格後:

ggplot() + 
    geom_bar(filter(dat.m, variable != "Other"), 
      mapping = aes(x = variable, y = value, fill = FF), 
      stat="identity") + 
    geom_text(filter(dat.m, variable == "Other"), 
      mapping = aes(x = variable, y = value, col = FF, label=FF), 
      position="stack", fontface="bold") + 
    guides(fill = FALSE, colour=FALSE, text=FALSE) 

enter image description here

的一些問題:

  • 圖例位置是硬編碼的。 (這裏是堆棧的max,如果鋼筋的高度相似,則很好)。文字可以在圖表背景的右上角嗎?
  • 文本是居中對齊的。使用hjust=0使其左對齊,但文本的左邊距位於類別的中間。 (這可以通過解決第一點來解決。)
  • 獎勵:如果類別文本標籤很長,是否可以「很好地」設置線條?
+0

至於第一個問題,使用'pmax',而不是'max'。我會使用默認指南雖然... – kohske 2014-10-01 06:47:39

回答

1

我最終選擇了annotate()來實現您的目標。您可以用這種方式指定文字的顏色。

ggplot(data = filter(dat.m, variable != "Other"), 
     aes(x = variable, y = value, fill = FF)) + 
     geom_bar(stat="identity") + 
     annotate("text", x = 2.55, y = 2.6, label = "F1", color = "#F8766D") + 
     annotate("text", x = 2.55, y = 2.7, label = "F2", color = "#00BA38") + 
     annotate("text", x = 2.55, y = 2.8, label = "F3", color = "#619CFF") + 
     theme(legend.position="none") 

enter image description here