2012-10-30 30 views
2

如果我有以下數據,並使用ggplot2繪製它,我得到:更改複合圖例標題

a <-c(0.3,0.3,0.3,0.3,0.3) 
b <-c(1:5,0.9,0.9,0.9,0.9,0.9) 
c <-c(1:5,0.5,0.5,0.5,0.5,0.5) 
z <-rep(1:5,5) 
df <- data.frame(y=c(a,b,c),x=c(z),line=c(rep("1",5), 
rep("2",5),rep("3",5),rep("2",5),rep("3",5))) 

library(ggplot2) 

a <- ggplot(df,aes(x=x,y=y,fill=line,shape=line,group=line)) +  
      geom_line(aes(linetype=line),size=1) +    
    scale_linetype_manual(values=c("dashed","solid", "dotdash")) + 
      geom_point(size=3) + scale_shape_manual(values=c(25,23,21,25,23)) +  
    scale_fill_manual(values=c("red", "blue", "yellow","red", "blue")) 

如果我想指定的傳奇頭銜,我可以做許多事情一樣

a + labs(shape = "MY TITLE HERE") # or 

a <- ggplot(df,aes(x=x,y=y,fill=line,shape=line,group=line)) +  
      geom_line(aes(linetype=line),size=1) +    
    scale_linetype_manual(values=c("dashed","solid", "dotdash")) + 
      geom_point(size=3) + scale_shape_manual(values=c(25,23,21,25,23),name="MY 
      TITLE HERE") +  
    scale_fill_manual(values=c("red", "blue", "yellow","red", "blue")) 

enter image description here

然而,所有的這些選擇打破了複合傳說成其單獨的映射paramters。

如何維護與linetypeshapefill的複合圖例並更改圖例標題?

回答

5

ggplot2具有相同標籤的所有尺度將被組合在一起,所以你需要這樣做:

  1. (可選)與您的標籤創建一個變量,例如scale_label
  2. 將相同的標籤作爲第一個參數傳遞給每個比例。

例如:

scale_label <- "My custom title" 

a <- ggplot(df,aes(x=x,y=y,fill=line,shape=line,group=line)) +  
    geom_line(aes(linetype=line),size=1) +    
    scale_linetype_manual(scale_label, values=c("dashed","solid", "dotdash")) + 
    geom_point(size=3) + 
    scale_shape_manual(scale_label, values=c(25,23,21,25,23)) +  
    scale_fill_manual(scale_label, values=c("red", "blue", "yellow","red", "blue")) 
    #scale_shape("Title") 
print(a) 

enter image description here

+0

相當畢竟簡單,非常感謝你@Andrie –