【问题标题】:Apply legend label to fill and color in ggplot在ggplot中应用图例标签来填充和着色
【发布时间】:2021-02-09 00:40:18
【问题描述】:

我正在为相同的数据系列制作许多图,例如,线图和带状图。然后我手动分配标签,使图例看起来不错。有没有办法避免像下面这样多次输入标签,只需执行一次并应用到所有比例?

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"))

提前致谢!

【问题讨论】:

  • 修改数据,使gender 列的值为Female 和Male

标签: r ggplot2 dplyr tidyverse


【解决方案1】:
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

【讨论】:

  • 喜欢 Jabba 对数刻度参考 +1。
【解决方案2】:

或者创建一个命名向量。将“其他”保留为 NA 的缺点(尽管在这种情况下只有 NA)。

我还没有适应 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).

reprex package (v0.3.0) 于 2021-02-09 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 2019-08-19
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 2022-07-07
    • 2012-12-17
    相关资源
    最近更新 更多