Skip to content

Instantly share code, notes, and snippets.

@git-ashish
Forked from vkoul/plotting_avg_temp.md
Created March 26, 2019 07:11
Show Gist options
  • Save git-ashish/2dd00fe84522a7f4fc0e98fa75a5fe24 to your computer and use it in GitHub Desktop.
Save git-ashish/2dd00fe84522a7f4fc0e98fa75a5fe24 to your computer and use it in GitHub Desktop.
Average Monthly Temp in Germany between 1881-1991 and 2008-2018

loading the libraries

library(ggplot2)
library(readr)
library(tidyverse)
library(lubridate)

loading the data

d <- read_csv("https://vis4.net/data/temperature.csv")

checking the data

table(d$month)
table(d$year)

modifying the data: Getting the month column

d <- d %>% 
      mutate(month_new = month + 1) %>% 
      mutate(month_name = month(month_new, label = TRUE, abbr = FALSE))

Plotting the chart in ggplot

ggplot(d, aes(x = year, y = tmp)) +
  facet_grid(~ month_name, switch = "x") +
  geom_rect(data = subset(d, month_new %% 2 != 0),
            fill = c('grey92'), # to generate alternate shades in facets
            xmin = -Inf, xmax = Inf, 
            ymin = -Inf, ymax = Inf, alpha = 0.5)+
  geom_point(size = 0.2, color = "black", alpha = 0.5)+
  geom_smooth(method = "loess", size = 1.2, se = FALSE, color = '#ff00ff')+
  geom_smooth(method = "lm", formula = y ~ 1, se = FALSE, color = "#2166AC")+ # avg_lines
  theme_minimal() +
  theme(axis.text.x = element_blank(), 
        axis.title.x = element_blank(),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.spacing = unit(0, "lines"),# for break-free y-gridlines
        panel.grid.major.y = element_line(color = "grey80", size = 0.7),
        panel.ontop = TRUE,# gridlines on top of facets
        legend.position = "none")+
  labs(y = "Temperature °C")

Resultant ggplot Chart

rplot01

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment