In order to show the development of a time series and its respective growth rate, I opted for a facet plot, since plots with two y-axis aren't an option.
The issue now is that although the y-axis of the two plots are perfectly aligned, the tick marks on the x-axis are not, since the automatically occuring first NA
value of the growth rate, shifts these values to the left and thus the plots are off by a month.
I would like to know how it would be possible to include the first NA
value in the plot of the growth rate as an empty column, to serve as a placeholder.
library(data.table)
library(ggplot2)
library(cowplot)
library(lubridate)
library(tidyverse)
dt <- structure(list(DATUM = structure(c(18321, 18351, 18382, 18412,
18443, 18473, 18504, 18535, 18565), tzone = "UTC", tclass = "Date", class = "Date"),
value = c(70.696, 75.713, 75.713, 75.713, 75.213, 75.213,
75.213, 46.025, 46.025)), row.names = c(NA, -9L), class = c("data.table",
"data.frame"))
p.timeseries.plot <- dt %>%
melt(data = ., id.vars = c("DATUM"), measure.vars = c( "value")) %>%
ggplot(data = .) +
geom_line(aes(x = DATUM, y = value), color="steelblue", size =1.2) +
geom_point(aes(x = DATUM, y = value), size = 2) +
theme_light() +
scale_x_date(date_labels = "%Y-%m", date_breaks = "2 months") +
xlab("") +
ylab("")
p.growth.rate <- dt[
, .(DATUM
, growth.rate = round(log(value) - log(shift(value, n =1L, type="lag",fill = NA)),4)
)] %>%
melt(data = ., id.vars = c("DATUM"), measure.vars = c( "growth.rate")) %>%
ggplot(data = .) +
geom_col(aes(x = DATUM, y = value, fill = value >= 0)) +
scale_fill_manual(guide = FALSE, breaks = c(TRUE, FALSE), values=c("green", "red")) +
theme_light() +
scale_x_date(date_labels = "%Y-%m", date_breaks = "2 months") +
xlab("") +
ylab("")
cowplot::plot_grid(p.timeseries.plot, p.growth.rate, align = "v", ncol = 1, rel_heights = c(0.65, 0.35))
The output of the plot looks like this:
question from:
https://stackoverflow.com/questions/65560293/include-na-values-as-empty-values-in-a-facet-plot