我希望多条折线图在x轴上仅显示年份(而不是年份和月份)。我尝试使用BinaryWriter
格式化“年”,但是"%Y"
显示了年,月和日。
df2
答案 0 :(得分:2)
带有lubridate
包。
您可以使用scale_x_date
,因为您的日期是2015年和2016年的10月,所以我将日期移动了9个月,以便在图表中同时显示2015年和2016年。
library(lubridate)
df2 <- df %>%
gather(key = "variable", value = "value", -year) %>%
mutate(year = year - months(9))
ggplot(df2, aes(x = year, y = value)) +
geom_line(aes(color = variable, linetype = variable)) +
scale_color_manual(values = c("darkred", "steelblue")) +
scale_x_date(date_breaks = "1 year",date_labels = "%Y")
另一种方法是从日期列中提取年份为整数,并使用year
(整数)进行绘制,还需要指定休息时间。
df2 <- df %>%
gather(key = "variable", value = "value", -year) %>%
mutate(year = lubridate::year(year))
ggplot(df2, aes(x = year, y = value)) +
geom_line(aes(color = variable, linetype = variable)) +
scale_color_manual(values = c("darkred", "steelblue")) +
scale_x_continuous(breaks = c(2015,2016))
两个结果都在同一张图中。