Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

axis_canvas and ggplot hlines with same values are not aligned when scale_y_continuous uses expand argument #159

Open
martindurian opened this issue Jun 19, 2020 · 0 comments

Comments

@martindurian
Copy link

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) 
@martindurian martindurian changed the title axis_canvas lines do not match with the plot when scale_y_continuous with expand argument axis_canvas and ggplot hlines with same values are not aligned when scale_y_continuous uses expand argument Jun 19, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant