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

ggplot formatting a complex legend

I’m trying to make up a legend with multiple elements of points and lines. There are point data and a number of reference lines. A simple mock-up example is below.

require(tidyverse)

df <- iris %>% 
      mutate(Species = factor(Species))

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
       geom_point() +
       theme_bw() +
       geom_hline(aes(yintercept = 2.5, colour = "forestgreen"), size = 1, linetype = 2) +
       geom_hline(aes(yintercept = 3.5, colour = "dodgerblue",),  size = 1, linetype = 1)

This produces this plot:

enter image description here

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

However, two issues to solve here in the legend as follows:

  1. How to get the species values to plot in the legend just as points (not points and lines)?
  2. How to get the legend items for the reference lines to have the desired names (say "Upper" and "Lower" for example) rather than the colors specified for the lines, while still having the correct line colors and line types?

>Solution :

To fix the issue with the colors and the labels set your colors via scale_color_manual and use a named vector of colors. Second, to fix the issue with the legend keys you could use the override.aes argument of guide_legend to set the linetypes for the points to NA and vice versa the shape for the lines to NA. Note that when doing so, you have to keep an eye on the order of the legend entries.

library(ggplot2)

pal_color <- scales::hue_pal()(5)
pal_color[1:2] <- c("forestgreen", "dodgerblue")
names(pal_color) <- c("Upper", "Lower", levels(df$Species))

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
  geom_point() +
  theme_bw() +
  geom_hline(aes(yintercept = 2.5, colour = "Lower"),
    size = 1, linetype = 2
  ) +
  geom_hline(aes(yintercept = 3.5, colour = "Upper"),
    size = 1, linetype = 1
  ) +
  scale_color_manual(
    values = pal_color,
    breaks = names(pal_color)
  ) +
  guides(color = guide_legend(
    override.aes = list(
      linetype = c(1, 2, rep(NA, 3)),
      shape = c(rep(NA, 2), rep(16, 3))
    )
  ))

enter image description here

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