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

sba*_*bac 3 datetime r ggplot2

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

library(tidyverse)
theme_set(theme_minimal())

df <- tibble(
             year = as.character(c(2015, 2016)),
             v1 = c(3,10),
             v2 = c(7,18))

    df$year <- as.Date(df$year, "%Y")
    format(df$year, "%Y")
    #> [1] "2015" "2016"

    df2 <- df %>%
      gather(key = "variable", value = "value", -year)

    ggplot(df2, aes(x = year, y = value)) + 
      geom_line(aes(color = variable, linetype = variable)) + 
      scale_color_manual(values = c("darkred", "steelblue"))
Run Code Online (Sandbox Code Playgroud)

yif*_*yan 5

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

Run Code Online (Sandbox Code Playgroud)

另一种方法是从日期列中提取年份作为整数,并使用year(integer) 进行绘图,您还需要指定中断。

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))
Run Code Online (Sandbox Code Playgroud)

两者都会产生同一个图表。

在此输入图像描述