如何使用荧光笔列在 ggplot 中映射动态颜色?

How do you map dynamic colors in ggplot using a highlighter column?

我正在尝试使用荧光笔列和 gghighlight 仅在图中显示选定的汽车(来自 mtcars 数据集)。我希望颜色与突出显示的汽车相匹配,因为它们在同一行,但颜色会混在一起。

下面是一个使用 mtcars 的完全可重现的示例。

library(shiny)
library(tidyverse)
library(ggthemes)
library(gghighlight)

color_list <- c("darkred", "yellow3", "green4", "darkblue", "purple",
            "pink2", "burlywood1", "aquamarine", "orange3", "black")

mtcars_clean <- 
mtcars %>% 
rownames_to_column(var = "car") %>% 
head(10) %>% 
mutate(car_color = color_list) %>% 
glimpse()

View(mtcars_clean)

正如您从图片中看到的那样 link 每辆车都有一个特定的 car_color 应该在汽车突出显示时显示。

selected_cars <- c("Mazda RX4", "Hornet 4 Drive", "Valiant", "Merc 240D", "Duster 360")

mtcars_test <- 
mtcars_clean %>% 
mutate(highlighter = case_when(car %in% selected_cars ~ "yes",
                               T ~ "no"),
       car_color = case_when(highlighter == "yes" ~ car_color,
                             T ~ "#C4CED4"))

p_test <-
mtcars_test %>%
ggplot(aes(x = mpg, y = reorder(car, mpg, max))) +
geom_col(aes(fill = car)) +
geom_text(data = mtcars_test %>%
              filter(car %in% selected_cars),
          aes(label = mpg, x = mpg + 1, col = highlighter)) +
theme_fivethirtyeight() +
theme(legend.position = "none") +
labs(title = "MPG by Car") +
scale_color_manual(values = c("black")) +
gghighlight(car %in% selected_cars)

p_test + scale_fill_manual(name = p_test$data$car, values = p_test$data$car_color)

但是,从下图中可以看出,'Merc 240D'这辆车应该是aquamarine,但是却是burlywood1。 Valiant应该是pink2,但它是海蓝宝石。汽车不保留 car_color 列中属于它们的颜色。

同样奇怪的是 geom_text 保持正确的值,但是 car_color 移动。

来自 help(scale_fill_manual)

中的文档

Values: a set of aesthetic values to map data values to. The values will be matched in order (usually alphabetical) with the limits of the scale, or with breaks if provided. If this is a named vector, then the values will be matched based on the names instead. Data values that don't match will be given na.value.

我们可以使用它来稍微更改代码并使其按预期工作

cols <- p_test$data$car_color
names(cols) <- p_test$data$car
p_test + scale_fill_manual(values = cols)

或者我们可以使用 breaks

breaks: One of:
NULL for no breaks
waiver() for the default breaks (the scale limits)
A character vector of breaks
A function that takes the limits as input and returns breaks as output

例如。我们也可以

p_test + scale_fill_manual(values = p_test$data$car_color, breaks = p_test$data$car)

类似的方法可以与 aes 对象中的现有美学一起使用。