Last active
August 27, 2019 14:18
-
-
Save BenjaminWolfe/fcfc9693db5decdd417572f994d0c642 to your computer and use it in GitHub Desktop.
If you specify a vector of gridline colors, ggplot2 cycles through them
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) # dplyr, stringr, ggplot2 | |
library(lubridate) | |
#' The `sunspot.month` dataset as a tibble: | |
sunspots_reshaped <- | |
tibble( | |
sunspot_month = sunspot.month %>% | |
start() %>% | |
c(1) %>% | |
paste(collapse = "-") %>% | |
ymd() + | |
months(1:length(sunspot.month) - 1), | |
sunspots = sunspot.month | |
) | |
#' A function for labeling months concisely: | |
#' | |
#' * The first letter of each month | |
#' * Each January, the last 2 digits of the year | |
label_months <- function(sunspot_month) { | |
month_letter <- sunspot_month %>% format("%b") %>% str_sub(1, 1) | |
year_no_century <- sunspot_month %>% format("%y") | |
paste0( | |
month_letter, | |
"\n", | |
if_else(month(sunspot_month) == 1, year_no_century, "") | |
) | |
} | |
#' The plot of the sun cycle from 1996 to 2008: | |
p <- | |
sunspots_reshaped %>% | |
filter( | |
between(year(sunspot_month), 1996, 2008) | |
) %>% | |
ggplot() + | |
aes( | |
x = sunspot_month, | |
y = sunspots | |
) + | |
geom_area( | |
fill = "gray", | |
color = "gray70" | |
) + | |
scale_y_continuous( | |
expand = expand_scale(mult = c(0, .05)) | |
) + | |
scale_x_date( | |
date_breaks = "1 month", | |
labels = label_months, | |
expand = expand_scale(add = c(0, 0)) | |
) + | |
theme_minimal() + | |
theme( | |
axis.title.x = element_blank(), | |
panel.ontop = TRUE, | |
panel.grid.minor = element_blank(), | |
panel.grid.major = element_line(color = "gray60") | |
) | |
#' Totally busy as is: | |
p | |
#' Way prettier this way; `ggplot2` cycles through line colors! | |
p + | |
theme( | |
panel.grid.major.x = element_line( | |
color = c( | |
"gray60", NA, NA, | |
"white" , NA, NA, | |
"white" , NA, NA, | |
"white" , NA, NA | |
) | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment