2017-09-01 39 views
7

示例代碼和數字:刪除ggplot傳奇象徵,同時保留標籤

data <- data.frame(ID = c(LETTERS[1:26], paste0("A",LETTERS[1:26])), 
        Group = rep(c("Control","Treatment"),26), 
        x = rnorm(52,50,20), 
        y = rnorm(52,50,10)) 

ggplot(data, aes(y=y,x=x, label=ID, color=Group)) + 
    geom_text(size=8) + 
    scale_color_manual(values=c("blue","red")) + 
    theme_classic() + 
    theme(legend.text = element_text(color=c("blue","red"))) 

enter image description here

我試圖解決的是去除圖標符號(以下簡稱「A」)和着色組標籤(對照和治療),因爲它們出現在圖中(分別爲藍色和紅色)。

我已經試過:

geom_text(show_guide = F) 

但這只是刪除了傳說完全。

爲了保持簡單,我可以使用註釋......但想知道是否有圖例特定的解決方案。

ggplot(data, aes(y=y,x=x, label=ID, color=Group)) + 
    geom_text(size=8, show_guide=F) + 
    scale_color_manual(values=c("blue","red")) + 
    theme_classic() + 
    annotate("text",label="Control", color="blue",x=20,y=80,size=8) + 
    annotate("text",label="Treatment", color="Red",x=23,y=77,size=8) 
+0

相關:[在GGPLOT2圖例鍵改變符號(https://stackoverflow.com/questions/10405823/changing-the-symbol-in-在-傳說鍵合GGPLOT2)。 – Henrik

回答

1

由於速戰速決你可以調整傳說鍵,通​​過硬編碼你想要的信息,儘管周圍的其他方式 - 保持鍵和刪除標籤。

library(grid) 

GeomText$draw_key <- function (data, params, size) { 
    txt <- ifelse(data$colour=="blue", "Control", "Treatment") 
    # change x=0 and left justify 
    textGrob(txt, 0, 0.5, 
      just="left", 
      gp = gpar(col = alpha(data$colour, data$alpha), 
         fontfamily = data$family, 
         fontface = data$fontface, 
         # also added 0.5 to reduce size 
         fontsize = data$size * .pt* 0.5)) 
} 

而當你繪製你壓制圖例標籤,並使圖例的關鍵點擴大到適合文本。

ggplot(data, aes(y=y,x=x, label=ID, color=Group)) + 
    geom_text(size=8) + 
    scale_color_manual(values=c("blue","red")) + 
    theme_classic() + 
    theme(legend.text = element_blank(), 
     legend.key.width = unit(1.5, "cm")) 
+0

或(歐元)你可以亂七八糟的grobs https://stackoverflow.com/questions/23588127/match-legend-text-color-in-geom-text-to-symbol – user20650

+0

我喜歡這個答案,但我掙扎讓集團的標籤(控制和處理)與「集團」標題保持一致。 – Flammulation

+0

@Flammulation;更新 – user20650

3

另一種選擇是使用點標記(而不是字母「a」)作爲圖標符號,你可以用以下解決方法做:

  1. 取出geom_text傳奇。
  2. 添加一個「虛擬」點幾何,並將點標記大小設置爲NA,因此實際上沒有點被繪製,但會生成一個圖例。
  3. 覆蓋圖例中點標記的大小,以便點標記將出現在圖例關鍵字中以區分每個組。

ggplot(data, aes(y=y,x=x, label=ID, color=Group)) + 
    geom_text(size=8, show.legend=FALSE) + 
    geom_point(size=NA) + 
    scale_color_manual(values=c("blue","red")) + 
    theme_classic() + 
    labs(colour="") + 
    guides(colour=guide_legend(override.aes=list(size=4))) 

enter image description here

相關問題