如何使用ggplot仅在x轴上显示年份

时间:2019-10-04 16:20:06

标签: r datetime ggplot2

我希望多条折线图在x轴上仅显示年份(而不是年份和月份)。我尝试使用BinaryWriter格式化“年”,但是"%Y"显示了年,月和日。

df2

1 个答案:

答案 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))

两个结果都在同一张图中。

enter image description here