How can i add costumized ggplot() legend for one especific geom_line()

how can i plot this graph where the legend only shows the black geom_line only? Thank you

library(ggplot2)
# the data
x <- replicate(4, rnorm(100))
xmat <- matrix(x, ncol = 4, byrow = F)
m <- apply(xmat,1,mean)
m <- data.frame(cbind(value = m, Var1 = 1:100))
colnames(xmat) <- letters[1:4]
meltx <- as.data.frame(reshape2::melt(xmat))

# the plot
ggplot(data = meltx, aes(x=Var1, y = value, color = Var2)) +
  geom_line() +
  geom_line(data = m, aes(x = Var1, y = value ), color = "black", size = 2) +
  theme(legend.position = "right")

# I want legend of black line only (data = m).

>Solution :

If you want to have a legend you have to map on aestehtics, i.e. move color inside aes() too, set your desired via scale_color_manual and finally set the breaks so that only the black line is displayed in the legend:

library(ggplot2)

set.seed(123)

pal_color <- scales::hue_pal()(dplyr::n_distinct(meltx$Var2))
names(pal_color) <- levels(factor(meltx$Var2))

pal_color <- c(pal_color, blackline = "black")
ggplot(data = meltx, aes(x = Var1, y = value, color = Var2)) +
  geom_line() +
  geom_line(
    data = m, aes(x = Var1, y = value, color = "blackline"),
    linewidth = 2
  ) +
  scale_color_manual(values = pal_color, breaks = "blackline") +
  theme(legend.position = "right")

Leave a Reply