Home > Mobile >  Legend title for ggplot with several options
Legend title for ggplot with several options

Time:11-01

I am plotting density plots by groups with different colors and linetypes.

 ggplot(data = data, 
           aes(x=X, group=G, color=factor(G), linetype = factor(G)))  
           geom_density()

How can I change the legend title while keeping it as one legend?

CodePudding user response:

Your issue comes from the fact that when you add a legend title (e.g., using scale_color_discrete), you're only doing it for color and not linetype. The first plot is fine because the legends have identical arguments (i.e., neither is specified). You need to provide identical specifications for each legend in order to combine them. See this post for more information.

There may be other ways around this issue, but we can't say for certain since we can't access your dataset (data).

library(tidyverse)
data(mtcars)

# this is ok; one legend
ggplot(data = mtcars, 
       aes(x=mpg, group=cyl, color=factor(cyl), linetype = factor(cyl)))  
  geom_density()

# this is not ok; now two legends
ggplot(data = mtcars, 
       aes(x=mpg, group=cyl, color=factor(cyl), linetype = factor(cyl)))  
  geom_density()   scale_color_discrete("New Name?")

# this is ok again; back to one legend
ggplot(data = mtcars, 
       aes(x=mpg, group=cyl, color=factor(cyl), linetype = factor(cyl)))  
  geom_density()    
  scale_colour_manual(name = "New!", 
                      labels = c("4", "6", "8"),
                      values = c("red", "blue", "pink"))  
  scale_linetype_manual(name = "New!", 
                        labels = c("4", "6", "8"),
                        values = c(2, 4, 6))

  • Related