简体   繁体   English

应用图例 label 在 ggplot 中填充和着色

[英]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.我正在为相同的数据系列制作许多图,例如,一条线 plot 和一条色带 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).将“其他”保留为 NA 的缺点(尽管在这种情况下只有 NA)。

I have not scaled for Jabba.我还没有为 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)代表 package (v0.3.0) 于 2021 年 2 月 9 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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