Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a second legend in ggplot dot chart for a vertical line

Tags:

r

ggplot2

Here is a sample ggplot dot chart I created:

original plot

For this I used the following code:

mtcars$cyl<-as.character(mtcars$cyl)


ggplot(
   mtcars, 
  aes(fill=cyl, 
  y=gear, 
  x=mpg)) + 

  geom_line(aes(group = gear)) +
  geom_vline(xintercept = mean(mtcars$mpg), linetype="dotted", 
         color = "black", size=1) +

  geom_point(aes(color = cyl),size=5) +
  theme_bw() +
  theme(axis.line = element_line(colour = "black"),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    panel.background = element_blank())

What I actually want is a second legend describing that the dotted line is the overall mean. It could look for example like that: desired plot

How can I do that?

like image 995
Olympia Avatar asked Jan 19 '26 15:01

Olympia


1 Answers

This can be one solution:

library(tidyverse)

mtcars$cyl<-as.character(mtcars$cyl)

d_me <- 
  mtcars %>% 
  summarize(me =  mean(mpg)) %>% 
  mutate(var = "overall \n mean")


mtcars %>% 
ggplot(
  aes(fill=cyl, 
      y=gear, 
      x=mpg)) + 
  geom_line(aes(group = gear)) +
  geom_point(aes(color = cyl),size=5) +
  geom_vline(data = d_me, aes(xintercept = me, linetype = var), 
             color = "black", size=1) +
  scale_linetype_manual(values = "dotted", name = "") +
  theme_bw() +
  theme(axis.line = element_line(colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank())
like image 79
Ricardo González-Gil Avatar answered Jan 22 '26 05:01

Ricardo González-Gil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!