更改复合图例标题

时间:2012-10-30 13:58:04

标签: r ggplot2

如果我有以下数据并使用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

但是,所有这些选项都会将复合图例分解为单独的映射参数。

如何使用linetypeshapefill维护复合图例并更改图例标题?

1 个答案:

答案 0 :(得分:5)

ggplot2中,具有相同标签的所有比例都将组合在一起,因此您需要执行此操作:

  1. (可选)使用您的标签创建变量,例如scale_label
  2. 将相同的标签作为第一个参数传递给每个比例。
  3. 例如:

    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

相关问题