代码之家  ›  专栏  ›  技术社区  ›  tassones

ggplot2:更改轴文本的颜色以匹配组

  •  1
  • tassones  · 技术社区  · 2 年前

    使用 tidyverse mtcars 数据集,我正在绘制 model mpg 每辆车的。我想要每辆车的轴文本颜色 模型 以反映 make (例如,丰田=红色,凯迪拉克=蓝色等)。我该怎么做?

    示例数据集

    library(tidyverse)
    
    # Create make and model for each car
    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)
    
    head(mtcars)
    #> # A tibble: 6 × 4
    #>   car               make   model        mpg
    #>   <chr>             <chr>  <chr>      <dbl>
    #> 1 Mazda RX4         Mazda  RX4         21  
    #> 2 Datsun 710        Datsun 710         22.8
    #> 3 Hornet Sportabout Hornet Sportabout  18.7
    #> 4 Duster 360        Duster 360         14.3
    #> 5 Merc 240D         Merc   240D        24.4
    #> 6 Merc 230          Merc   230         22.8
    
    # How can I make the y-axis text color reflect the make of each model?
    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()
    

    创建于2023-12-06 reprex v2.0.2

    • 这里有一个类似的SO问题,它使用了一个只有两个类别的例子(这个例子有20个; link here )
    1 回复  |  直到 2 年前
        1
  •  2
  •   Allan Cameron    2 年前

    官方不支持在主题元素中使用矢量化颜色,但它确实有效,因此您可以执行以下操作:

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

    enter image description here

    就我个人而言,我会避免使用颜色和图例作为轴标签。为什么不直接用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")
    

    enter image description here

    推荐文章