user11326509
user11326509

Reputation:

ggplot not displaying every single year on x axis

enter image description hereTrying to plot a graph using ggplot, but I can't seem to figure out how to display every single year in the x axis.

This is what my code looks like:

library(dslabs)
data(temp_carbon)
#view(temp_carbon)

# line plot of annual global, land and ocean temperature anomalies since 1880
temp_carbon %>%
    select(Year = year, Global = temp_anomaly, Land = land_anomaly, Ocean = ocean_anomaly) %>%
    gather(Region, Temp_anomaly, Global:Ocean) %>%
    ggplot(aes(Year, Temp_anomaly, col = Region)) +
    geom_line(size = 1) +
    geom_hline(aes(yintercept = 0), col = colorblind_palette[8], lty = 2) +
    geom_label(aes(x = 2005, y = -.08), col = colorblind_palette[8],label = "20th century mean", size = 4) +
    ylab("Temperature anomaly (degrees C)") +
    xlim(c(1880, 2018)) +
    scale_color_manual(values = colorblind_palette) +
    ggtitle("Global, Land and Ocean Temperatures from 1880-2018")

Upvotes: 1

Views: 1199

Answers (1)

DHW
DHW

Reputation: 1267

It's going to be tricky to make that readable, but I think you're looking for scale_x_continuous with the following function-generated breaks and labels:


library(dslabs)
library(tidyverse)

data(temp_carbon)
#view(temp_carbon)

# line plot of annual global, land and ocean temperature anomalies since 1880
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")

Created on 2019-10-19 by the reprex package (v0.3.0)

Note that I had to remove everything utilizing colorblind_palette, as I couldn't find that object anywhere.

On reformatting labels for readability, check this out: https://stackoverflow.com/a/1331400/5693487

Upvotes: 1

Related Questions