user11326509
user11326509

Reputation:

need help displaying every 10th year on x axis ggplot graph

enter image description hereNeed help plotting every 10th year on the x axis.

temp_carbon %>%
  select(Year = year, Global = temp_anomaly, Land = land_anomaly, Ocean = ocean_anomaly) %>%
  gather(Region, Temp_anomaly, Global:Ocean) %>%
  drop_na() %>% 
  ggplot(aes(Year, Temp_anomaly, col = Region)) +
  geom_line(size = 1) +
  geom_hline(aes(yintercept = 0), lty = 2) +
  geom_label(aes(x = 2005, y = -.08),label = "20th century mean", size = 4) +
  ylab("Temperature anomaly (degrees C)") +
  scale_x_continuous(breaks = function(x) exec(seq, !!!x), 
                     labels = function(x) x, 
                     limits = c(1880, 2018)) +
  ggtitle("Global, Land and Ocean Temperatures from 1880-2018")

The above is my current code and the picture above shows that the x axis is very messy and you cant see the years, how do i fix this?

Upvotes: 1

Views: 1980

Answers (1)

deepseefan
deepseefan

Reputation: 3791

If this is the output you want, read to see what I did along.

Output

ts_out

Save your data as df

df <- temp_carbon %>%
  select(Year = year, Global = temp_anomaly, Land = land_anomaly, Ocean = ocean_anomaly) %>%
  gather(Region, Temp_anomaly, Global:Ocean) %>%
  drop_na()

Then, use lubridate to convert it to proper date

df$Year <- lubridate::ymd(df$Year, truncated = 2L)
# [1] "1880-01-01" "1881-01-01" "1882-01-01" "1883-01-01" "1884-01-01" "1885-01-01"
# This sets the month and date on Jan-01. 

Prepare the base which shows every thenth year on x-axis. You can calculate every tenth year using seq(min(year(df$Year)), max(year(df$Year)), by = 10)

base <- ggplot(df, aes(year(Year), Temp_anomaly, col = Region)) + 
    theme(axis.text.x = element_text(angle = 90, size = 7, vjust =0.5, margin=margin(5,0,0,0))) +
    scale_x_continuous(
        "Year", 
        labels = as.character(seq(min(year(df$Year)), max(year(df$Year)), by = 10)), 
        breaks = seq(min(year(df$Year)), max(year(df$Year)), by = 10), 
        expand=c(0,0)
    )

Finally your subsequent layers to the plot:

base + geom_line(size = 1) +
  geom_hline(aes(yintercept = 0), lty = 2) +
  geom_label(aes(x = 2005, y = -.08),label = "20th century mean", size = 4) +
  ylab("Temperature anomaly (degrees C)") + 
  ggtitle("Global, Land and Ocean Temperatures from 1880-2018")

Upvotes: 5

Related Questions