You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot2:如何让坐标轴文本颜色与车辆品牌(make)匹配

给ggplot2的Y轴标签按车辆品牌设置不同颜色

要让Y轴上的车型(model)文本颜色对应其品牌(make),可以通过以下步骤实现:

  1. 定义品牌-颜色映射:为每个品牌指定对应颜色,比如Toyota设为红色、Cadillac设为蓝色等。
  2. 匹配车型对应的颜色:根据处理后的数据集,提取每个车型对应的品牌颜色,需保证和Y轴标签的排序一致。
  3. 在ggplot主题中设置轴文本颜色:利用theme()里的axis.text.y参数,通过element_text()的colour参数传入匹配好的颜色向量。

完整代码示例

library(tidyverse)

# 处理数据集:提取品牌和车型
mtcars <- mtcars %>%
  rownames_to_column(var = 'car') %>%
  filter(!car %in% c('Mazda RX4 Wag', 'Hornet 4 Drive', 'Valiant', 'Ford Pantera L')) %>%
  separate_wider_delim(car, " ", names = c('make', 'model'), cols_remove = FALSE) %>%
  select(car, make, model, mpg)

# 1. 定义品牌与颜色的映射(可按需自定义)
make_colors <- c(
  Mazda = "red",
  Datsun = "blue",
  Hornet = "green",
  Duster = "orange",
  Merc = "purple",
  Toyota = "red",
  Cadillac = "blue"
)

# 2. 提取每个车型对应的颜色:按Y轴标签顺序匹配
model_colors <- mtcars %>%
  arrange(model) %>%  # 确保与Y轴排序一致
  distinct(model, make) %>%
  pull(make) %>%
  recode(!!!make_colors)

# 3. 绘图并设置Y轴文本颜色
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(colour = model_colors)
  )

说明

  • make_colors是自定义的品牌颜色映射,可根据实际品牌列表补充或修改颜色值。
  • arrange(model)确保提取的颜色顺序和Y轴上车型的显示顺序一致,避免颜色错位。
  • recode(!!!make_colors)通过非标准求值将品牌名称替换为对应的颜色值。

内容的提问来源于stack exchange,提问作者tassones

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 13:55:30