【问题标题】:Rename Legend Values in R在 R 中重命名图例值
【发布时间】:2020-12-23 10:52:06
【问题描述】:

通过ggplot2,我学会了重命名 X 轴、Y 轴和各个图例。但是,我也想重命名图例值。

例如,为简单起见,我在数据集中使用 0 表示男性,1 表示女性,当我显示它并将性别映射到审美时,我不希望图例读取数据的 0 或 1值,但男性和女性。

或者,在下面的示例中,使用“4 轮驱动”、“前轮驱动”、“后轮驱动”代替“4”、“f”和“r”将使图表更易于理解。

library(tidyverse)

ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy, color = drv)) + labs(x = "Engine Size (Liters)", y = "Fuel Efficiency (Miles per Gallon)", color = "Drive")

  • 一种选择是打开 Excel 文件并将特定列中的所有 0 和 1 更改为“男性”和“女性”。
  • 另一种选择是重命名 R 中的值,但我完全不知道该怎么做。我对 R 很陌生。

我希望用一种简单的方法来重命名图例中显示的值。

【问题讨论】:

    标签: r ggplot2 axis-labels


    【解决方案1】:

    您可以在比例中使用labels 参数来自定义标签。您可以为 labels 参数提供函数或字符向量。

    library(tidyverse)
    
    ggplot(data = mpg) + 
      geom_point(mapping = aes(x = displ, y = hwy, color = drv)) + 
      labs(x = "Engine Size (Liters)", y = "Fuel Efficiency (Miles per Gallon)", color = "Drive") +
      scale_colour_discrete(
        labels = c("4" = "4 wheel drive",
                   "f" = "front wheel drive",
                   "r" = "rear wheel drive")
      )
    

    reprex package (v0.3.0) 于 2020 年 12 月 23 日创建

    【讨论】:

    • 非常感谢。只是为了确保我理解:scale_shape_discretescale_linetype_discrete 等也适用?
    • 是的,它甚至可以使用连续刻度(但应与计算或提供的中断的长度相匹配)和位置刻度 (scale_x/y_discrete/continuous)。所以,任何本质上产生标签的规模。
    【解决方案2】:

    你可以recode绘图前的值:

    library(dplyr)
    library(ggplot2)
    
    mpg %>%
      mutate(drv = recode(drv, "4" = "4 wheel drive", 
                                "f" = "front wheel drive", 
                                "r" = "rear wheel drive")) %>%
      ggplot() + 
      geom_point(aes(x = displ, y = hwy, color = drv)) + 
      labs(x = "Engine Size (Liters)", 
           y = "Fuel Efficiency (Miles per Gallon)", 
           color = "Drive")
    

    【讨论】:

      猜你喜欢
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 2021-11-26
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多