sbac
sbac

Reputation: 2081

How to show only years in x axis using ggplot

I want my multiple line chart to show only years (not years and months) on x axis. I tried to format "years" with "%Y" but df2 shows days, months and year.

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

Upvotes: 3

Views: 8289

Answers (1)

Yifu Yan
Yifu Yan

Reputation: 6106

With lubridate package.

You can use scale_x_date, since your date is Oct in 2015 and 2016, So I shifted dates by 9 months to display both 2015 and 2016 in the graph.

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

Another way would be extracting year from the date column as integer, and use year(integer) to plot, you also need to specify breaks.

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

Both results in the same graph.

enter image description here

Upvotes: 7

Related Questions