更改图例中的标签名称

时间:2021-05-16 12:10:04

标签: r ggplot2 graph

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

我的代码

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

这是制作出来的图。

enter image description here

我尝试添加以下代码行

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

但我收到此错误

<块引用>

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

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

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

1 个答案:

答案 0 :(得分:0)

修改标签的一种方法是在绘制数据之前更改数据。在不知道 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),您仍将在 colour = cruise 中指定 ggplot()


正如亚历克斯所建议的,您可能只需要指定一个 scale_colour_*

相关问题