1

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")
DHW
  • 870
  • 7
  • 22

1 Answers1

1

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

DHW
  • 870
  • 7
  • 22
  • Yeah i had a look at the reformatting labels link but im not sure how to fix it –  Oct 20 '19 at 04:24
  • You almost certainly need to either narrow the timeframe being visualized or not have a tickmark for every single year. Otherwise, the marks will need to be *very* small and vertical - probably still not at all readable. – DHW Oct 20 '19 at 14:27