Home > Blockchain >  How to combine line and bordered point into 1 legend?
How to combine line and bordered point into 1 legend?

Time:06-24

ggplot2::ggplot(data.frame("Year" = 2013:2022, "Value" = rnorm(10)), 
       aes(Year, Value, color = "Name with Spaces", fill = "Name with Spaces"))   
  geom_line()  
  geom_point(color = "blue", pch = 21)  
  scale_color_manual(values = "red")  
  scale_fill_manual(values = "yellow")

My code above will show the following plot in R

ggplot image

How can I put the two legend items into one, that is "a red line pass beneath the blue-bordered yellow point"?

CodePudding user response:

One option would be to put the label in a column of your dataframe an map this column on the color and fill aes:

library(ggplot2)

set.seed(123)

df <- data.frame("Year" = 2013:2022, "Value" = rnorm(10), color = "Name with Spaces")

ggplot(df, aes(Year, Value, color = color, fill = color))  
  geom_line()  
  geom_point(color = "blue", shape = 21, size = 2)  
  scale_color_manual(values = "red")  
  scale_fill_manual(values = "yellow")

CodePudding user response:

Another option is to use identical name and labels values for both color and fill scales.

library(tidyverse)

ggplot2::ggplot(data.frame("Year" = 2013:2022, "Value" = rnorm(10)),
                aes(Year, Value, color = "Name with Spaces", fill = "Name with Spaces"))  
  geom_line()  
  geom_point(color = "blue", pch=21, size = 2.25, stroke = 1)  
  scale_color_manual(name = "",
                     labels = "Name with Spaces",
                     values = "red")  
  scale_fill_manual(name = "",
                    labels = "Name with Spaces",
                    values = "yellow")

*Note: You don't need to adjust the size and stroke in geom_point. I just wanted to show the colors better.

Output

enter image description here

  • Related