【问题标题】:Changing label names in a legend更改图例中的标签名称
【发布时间】:2021-05-16 12:10:04
【问题描述】:

我正在尝试重命名我的图例中的标签。

我的代码

ggplot(BioPlusMetrics, aes(x = depth, y = temperature, colour = cruise)) +
  labs(x = "Depth", y = "Temperature", colour = "Month") +
  geom_line(size=1, linetype=2)+
  geom_point()+
  scale_color_hue(direction = -1) +
  scale_x_reverse()+
  scale_y_continuous(position="right")+
  coord_flip()

这是生成的图形。

我已尝试添加以下代码行

 + scale_colour_discrete(labels=c("August","May","November","October")) +

但我得到了这个错误

“颜色”的比例已经存在。为“颜色”添加另一个比例,它将替换现有比例。

谁能帮我把我的图例标签重命名为

"August", "May", "November" and "October"

【问题讨论】:

  • 问题是您同时使用了scale_colour_huescale_colour_discrete,这就是为什么您会收到错误提示颜色已经存在。尝试删除scale_colour_hue,因为您没有指定色轮
  • 如果您创建一个小的可重现示例以及预期的输出,这将更容易提供帮助。阅读how to give a reproducible example

标签: r ggplot2 graph


【解决方案1】:

修改标签的一种方法是在绘制数据之前更改数据。在不知道BioPlusMetrics 数据结构的情况下,很难提供一个完美的示例。



如果您的数据中有一个日期列(日期格式),那么您可以提取月份的名称,并将其放入单独的列中,例如:

BioPlusMetrics <- BioPlusMetrics %>% 
  mutate(
    month_name = format(date, '%B')
  )

基本上,format(date, '%B') 获取您的日期,并将其“重新格式化”为由'%B' 指定的“月份全名”格式。有关不同格式的列表,请参阅 https://www.r-bloggers.com/2013/08/date-formats-in-r/。 (编辑:查看https://www.stat.berkeley.edu/~s133/dates.html 获取日期和日期时间格式列表)。

或者使用lubridate 包的替代方案:

BioPlusMetrics <- BioPlusMetrics %>%
  mutate(
    month_name = lubridate::month(date, label = TRUE, abbr = FALSE)
    # label = TRUE means we get the name of the month rather than the number of the month
    # abbr = FALSE means we get the full name, not the 3 letter abbreviation (eg Oct)
  )

一旦您的数据中有完整的月份名称,您就可以修改ggplot 的代码,使用colour = month_name 而不是colour = cruise

# ggplot(BioPlusMetrics, aes(x = depth, y = temperature, colour = cruise)) +
ggplot(BioPlusMetrics, aes(x = depth, y = temperature, colour = month_name)) +
  labs(x = "Depth", y = "Temperature", colour = "Month") +
  geom_line(size=1, linetype=2)+
  geom_point()+
  scale_color_hue(direction = -1) +
  scale_x_reverse()+
  scale_y_continuous(position="right")+
  coord_flip()


或者,您可以使用ifelse 来修改cruise 的值:

BioPlusMetrics <- BioPlusMetrics %>%
  mutate(
    cruise = ifelse(cruise == 'Aug 2013', 'August', cruise),
    # ifelse() above may be read as: "If cruise is 'Aug 2013', change it to 'August', otherwise we keep the existing value in the cruise column"

    cruise = ifelse(cruise == 'May 2014', 'May', cruise),
    # copy and repeat for each value you want to change...
  )

如果您修改cruise 列(而不是在其他示例中创建month_name),您仍将在ggplot() 中指定colour = cruise


正如 Alex 所建议的,您可能只需要指定一个 scale_colour_*

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2019-02-19
    • 2018-06-10
    • 2014-05-31
    • 1970-01-01
    • 2017-12-24
    • 2018-01-17
    • 1970-01-01
    • 2021-01-29
    相关资源
    最近更新 更多