axis_canvas and ggplot hlines with same values are not aligned when scale_y_continuous uses expand argument
martindurian opened this issue · 0 comments
martindurian commented
ggplot v3.3.0
cowplot v1.0
when ggplot uses scale_y_continuous with expand argument, equal values on plot and axis_canvas are not aligned.
when I remove the expand argument, then everything is nicely aligned
library(tidyverse)
library(cowplot)
# dataframe -----
plt_df <- tribble(
~Week_Day, ~Week_Day_Name, ~workday, ~Week_day_consumption,
1, "Mon", TRUE, 23376,
2, "Tue", TRUE, 23843,
3, "Wed", TRUE, 20790,
4, "Thu", TRUE, 20993,
5, "Fri", TRUE, 18963,
6, "Sat", FALSE, 15387,
7, "Sun", FALSE, 17997
)
# calculate averages for week parts -----
avg_df <- summarise(group_by(plt_df, workday), part_mean = mean(Week_day_consumption))
base_plt <- ggplot(plt_df, aes(x = Week_Day, y = Week_day_consumption)) +
geom_col(aes(fill = workday)) +
geom_hline(data = avg_df, aes(yintercept = part_mean, color = workday)) +
theme(legend.position = "none") +
labs(title = "without expansion")
# create base plot with expansion -----
base_plt_exp <- base_plt +
labs(title = "with expansion") +
scale_y_continuous(expand = expansion(mult = c(0.05, 0.1)))
# alternative y axis plot annotate average lines -----
annotation_plt <- axis_canvas(base_plt,
axis = "y",
data = avg_df
) +
geom_hline(aes(yintercept = part_mean))
annotation_plt_exp <- axis_canvas(base_plt_exp,
axis = "y",
data = avg_df
) +
geom_hline(aes(yintercept = part_mean))
# insert alternative y axis ------
plot_composed <- ggdraw(insert_yaxis_grob(base_plt, annotation_plt, grid::unit(0.1, "null"),
position = "right"
))
plot_composed_exp <- ggdraw(insert_yaxis_grob(base_plt_exp, annotation_plt_exp, grid::unit(0.1, "null"),
position = "right"
))
plot_grid(plot_composed, plot_composed_exp)