官方不支持在主题元素中使用矢量化颜色,但它确实有效,因此您可以执行以下操作:
mtcars %>%
ggplot(aes(x = mpg, y = model)) +
geom_point() +
labs(y = NULL) +
scale_x_continuous(breaks = seq(0, 35, 5), limits = c(0,35)) +
theme_bw() +
theme(axis.text.y = element_text(
color = scales::hue_pal()(length(levels(factor(mtcars$make))))[
as.numeric(factor(mtcars$make))]
))
就我个人而言,我会避免使用颜色和图例作为轴标签。为什么不直接用facet标记呢?
mtcars %>%
ggplot(aes(x = mpg, y = model)) +
geom_point() +
labs(y = NULL) +
scale_x_continuous(breaks = seq(0, 35, 5), limits = c(0,35)) +
theme_minimal() +
theme(panel.spacing.y = unit(0, "mm"),
strip.text.y.left = element_text(angle = 0),
strip.background = element_rect(fill = "gray90", color = "white",
linewidth = 1.5),
strip.placement = "outside") +
facet_grid(make~., scales = "free_y", space = "free_y", switch = "y")