Skip to content

Instantly share code, notes, and snippets.

@sebastianrothbucher
Last active March 30, 2022 03:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sebastianrothbucher/de847063f32fdff02c83b75f59c36a7d to your computer and use it in GitHub Desktop.
Save sebastianrothbucher/de847063f32fdff02c83b75f59c36a7d to your computer and use it in GitHub Desktop.
Two scales in ggplot2
# two scales in one diag (not always recommended, but I WANT that now)
# some reading up: https://stackoverflow.com/questions/3099219/plot-with-2-y-axes-one-y-axis-on-the-left-and-another-y-axis-on-the-right/3101876#
library(ggplot2)
library(lubridate)
dt <- data.frame(when=ymd(c(20180320,20180321, 20180323, 20180324, 20180325)), numinter=c(1, 5, 4, 3, 4), prod=c(0.95, 0.5, 0.7, 0.75, 0.6)) # pure fiction
ggplot() +
geom_bar(mapping = aes(x = dt$when, y = dt$numinter), stat = "identity", fill = "grey") +
geom_line(mapping = aes(x = dt$when, y = dt$prod*5), size = 2, color = "blue") +
scale_x_date(name = "Day", labels = NULL) +
scale_y_continuous(name = "Interruptions/day", sec.axis = sec_axis(~./5, name = "Productivity % of best", labels = function(b) { paste0(round(b * 100, 0), "%")})) +
theme(
axis.title.y = element_text(color = "grey"),
axis.title.y.right = element_text(color = "blue"))
# two scales in one diag (alternate approeach suggested on s-o / here: https://github.com/tidyverse/ggplot2/wiki/Align-two-plots-on-a-page)
# some reading up: https://stackoverflow.com/questions/3099219/plot-with-2-y-axes-one-y-axis-on-the-left-and-another-y-axis-on-the-right/3101876#
library(ggplot2)
library(lubridate)
dt <- data.frame(when=ymd(c(20180320,20180321, 20180323, 20180324, 20180325)), numinter=c(1, 5, 4, 3, 4), prod=c(0.95, 0.5, 0.7, 0.75, 0.6)) # pure fiction
dtF <- rbind(
data.frame(when=dt$when, num=dt$prod, what="Productivity % of best"),
data.frame(when=dt$when, num=dt$numinter, what="Interruptions/day"))
secondFacet <- FALSE # see below
ggplot(data = dtF, mapping = aes(x = when, y = num)) +
facet_grid(what~., scale = "free") +
geom_bar(data=dtF[dtF$what=="Interruptions/day",], stat = "identity", fill = "grey") +
geom_line(data=dtF[dtF$what=="Productivity % of best",], size = 2, color = "blue") +
scale_y_continuous(name = NULL, labels = function(b) {
if(!secondFacet) {
secondFacet <<- TRUE # this is a little cray (and relies on dtF seq = facet seq; works though)
return(paste0(round(b * 100, 0), "%"))
}else{
return(b)
}
}) +
scale_x_date(name = "Day", labels = NULL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment