简体   繁体   中英

Apply legend label to fill and color in ggplot

I am making a number of plots where for the same data series I produce, for example, a line plot and a ribbon plot. I then manually assign labels so that the legend looks nice. Is there a way to avoid typing out the labels multiple times like the below and simply do it once and have it apply to all the scales?

library(tidyverse)
starwars %>% 
  ggplot(aes(x=mass, y=height, color=gender, fill=gender)) +
  geom_line() +
  geom_point() +
  scale_color_brewer(labels=c("Female", "Male")) +
  scale_fill_brewer(labels=c("Female", "Male"))

Thanks in advance!

library(tidyverse)
starwars %>% filter(mass > 1000)
  mutate(gender = case_when(
    gender == "masculine" ~ "Male",
    gender == "feminine"  ~ "Female",
    TRUE ~ "Other")) %>%
  ggplot(aes(x=mass, y=height, color=gender, group = gender, fill=gender)) +
  geom_line() +
  geom_point() +
  scale_x_log10() # Because Jabba is an absolute unit

在此处输入图像描述

Or create a named vector. Disadvantage to keep "other" as NA (although else, there is only NA in this case).

I have not scaled for Jabba.

library(tidyverse)

mylabels <- c(feminine = "Female", masculine = "Male")
starwars %>% 
  ggplot(aes(x=mass, y=height, color=gender, fill=gender)) +
  geom_line() +
  geom_point() +
  scale_color_brewer(labels=mylabels) +
  scale_fill_brewer(labels=mylabels)
#> Warning: Removed 29 row(s) containing missing values (geom_path).
#> Warning: Removed 29 rows containing missing values (geom_point).

Created on 2021-02-09 by the reprex package (v0.3.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM