簡體   English   中英

應用圖例 label 在 ggplot 中填充和着色

[英]Apply legend label to fill and color in ggplot

我正在為相同的數據系列制作許多圖,例如,一條線 plot 和一條色帶 plot。 然后我手動分配標簽,使圖例看起來不錯。 有沒有辦法避免像下面那樣多次輸入標簽,只需執行一次並將其應用於所有比例?

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

提前致謝!

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

在此處輸入圖像描述

或者創建一個命名向量。 將“其他”保留為 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).

代表 package (v0.3.0) 於 2021 年 2 月 9 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM