Skip to content

Instantly share code, notes, and snippets.

@andrewheiss
Last active December 4, 2023 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewheiss/c102b917c20ca776aef4fbed90d76ae9 to your computer and use it in GitHub Desktop.
Save andrewheiss/c102b917c20ca776aef4fbed90d76ae9 to your computer and use it in GitHub Desktop.
library(tidyverse)

example_draws <- tribble(
  ~category, ~shapes,
  FALSE,     c(10, 10, 13),
  TRUE,      c(7, 7, 8)
) |> 
  mutate(draws = map(shapes, ~{
    withr::with_seed(1234, {
      brms::rdirichlet(n = 500, alpha = .x) |>
        data.frame() |> 
        set_names(LETTERS[1:3]) |> 
        mutate(draw = 1:n())
    })
  })) |> 
  unnest(draws) |> select(-shapes) |> 
  pivot_longer(cols = c(LETTERS[1:3]), names_to = "outcome", values_to = "prop")

plot_thing <- example_draws |> 
  ggplot(aes(x = draw, y = prop, fill = outcome)) +
  geom_col(position = position_stack(), linewidth = 0, width = 1) +
  facet_wrap(vars(category)) 
plot_thing

ggsave(
  filename = "~/Desktop/plot_with_cairo.png", 
  plot = plot_thing + labs(title = "Saved as Cairo PNG"),
  width = 7.5, height = 4,
  device = png, type = "cairo", dpi = 300
)

ggsave(
  filename = "~/Desktop/plot_with_agg.png", 
  plot = plot_thing + labs(title = "Saved as agg PNG"),
  width = 7.5, height = 4,
  device = ragg::agg_png, res = 300
)

ggsave(
  filename = "~/Desktop/plot_with_cairo.pdf", 
  plot = plot_thing + labs(title = "Saved as Cairo PDF"),
  width = 7.5, height = 4,
  device = cairo_pdf
)
plot_thing_area <- example_draws |> 
  ggplot(aes(x = draw, y = prop, fill = outcome)) +
  geom_area() +
  facet_wrap(vars(category)) 
plot_thing_area

ggsave(
  filename = "~/Desktop/area_plot_with_agg.png", 
  plot = plot_thing_area + labs(title = "Saved as agg PNG, geom_area()"),
  width = 7.5, height = 4,
  device = ragg::agg_png, res = 300
)

ggsave(
  filename = "~/Desktop/area_plot_with_cairo.pdf", 
  plot = plot_thing_area + labs(title = "Saved as Cairo PDF, geom_area()"),
  width = 7.5, height = 4,
  device = cairo_pdf
)

Created on 2023-12-04 with reprex v2.0.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment