Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change composite legend title

Tags:

r

ggplot2

If I have the following data and plot it using ggplot2 I get:

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"))

If I want to specify the title of the legend I can do a number of things like

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

However, all of these options break the composite legend up into their separate mapping paramters.

How do I maintain the composite legend with linetype,shape and fill and change the legend title?

like image 467
user1317221_G Avatar asked Nov 22 '25 01:11

user1317221_G


1 Answers

In ggplot2 all scales with the same label will be grouped together, so you need to do this:

  1. (optional) Create a variable with your label, e.g. scale_label
  2. Pass the same label to each scale as the first argument.

For example:

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

like image 99
Andrie Avatar answered Nov 23 '25 17:11

Andrie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!