ktm
ktm

Reputation: 119

How do I remove superfluous legend (titles) in ggplot?

I am trying to remove the "series" legend since I have added my own (mainly to change the legend title). Below my code (should be reproducible)

p1 image output

df<-data.frame(
  "time"=c(100, 75, 50, 25, 0, -25),
  "nativ"=c("start", "75", "50", "25","home","end"),
  "series"=c("A", "A","A", "A", "A","A"),
  "value"=runif(n = 6,min = 0,max = 20)
)

serlabel=c("start", "75", "50", "25","home","end")

p2<-ggplot2::ggplot(
  df, 
  ggplot2::aes(time,
               value,
               group=1
  )) + 
  ggplot2::geom_line(
    ggplot2::aes(colour = series, linetype=series))+
  #
  ggplot2::labs(x= "Locations", 
                y="APC", 
                colour=paste(
                  "New legend title")
  )+ #add variiable to function if fpkm or fc
  ggplot2::scale_x_reverse(breaks = c(100, 75, 55, 35, 10, -20),
                           labels = serlabel, #enter serieslabel variable
                           expand=c(0,0))+
  ggplot2::theme_bw()
p2

I have tried to remove the series legend by adding

+ggplot2::theme(legend.title = ggplot2::element_blank())

but this removes both titles. There must be a cleaner way to do this. Does anyone know how?

Upvotes: 3

Views: 508

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76412

In labs use the same title for the linetype legend.

ggplot(df, aes(time, value)) +
  geom_line(
    aes(colour = series, linetype = series)
  ) +
  labs(
    x = "Locations", 
    y = "APC", 
    colour = "New legend title",
    linetype = "New legend title"
  ) +
  scale_x_reverse(
    breaks = c(100, 75, 55, 35, 10, -20),
    labels = serlabel, #enter serieslabel variable
    expand = c(0, 0)
  ) +
  theme_bw()

enter image description here

Upvotes: 1

Ian Campbell
Ian Campbell

Reputation: 24790

Add scale_linetype(guide = FALSE):

ggplot(df, aes(time, value, group=1)) + 
  geom_line(aes(colour = series, linetype=series)) +
  labs(x= "Locations", y="APC", colour= "New legend title") +
  scale_x_reverse(breaks = c(100, 75, 55, 35, 10, -20),
                           labels = serlabel, expand=c(0,0))+
  scale_linetype(guide = FALSE) +
  theme_bw()

enter image description here

Upvotes: 2

Related Questions