修改标签的一种方法是在绘制数据之前更改数据。在不知道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_*。