Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading