jrnold / ggthemes

Additional themes, scales, and geoms for ggplot2
http://jrnold.github.io/ggthemes/
1.31k stars 229 forks source link

`theme_tufte` with `geom_rangeframe` doesn't work with `facet_wrap` #131

Closed albert-ying closed 2 years ago

albert-ying commented 3 years ago

Hi, I'm recently looking for ways to create the base-R styled axis in ggplot. I found your example code that works well to me:

p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  scale_x_continuous(breaks = extended_range_breaks()(mtcars$wt)) +
  scale_y_continuous(breaks = extended_range_breaks()(mtcars$mpg)) +
  ggtitle("Cars")

p +
  geom_rangeframe() +
  coord_cartesian(clip="off") +
  theme_tufte()

However, when I do it with facet_wrap, it gives the weird output:

p + geom_rangeframe() +
  coord_cartesian(clip="off") +
  theme_tufte() +
  facet_wrap(~am)
image

I'm wondering if there is a way to get this style work for facets? Thank you so much!

grantmcdermott commented 3 years ago

For faceting with theme_tufte, it's best to generate your own geom_rangeframe data.

library(ggplot2)
library(ggthemes)

p = ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  scale_x_continuous(breaks = extended_range_breaks()(mtcars$wt)) +
  scale_y_continuous(breaks = extended_range_breaks()(mtcars$mpg)) +
  ggtitle("Cars")

p + 
  geom_rangeframe(
    data = data.frame(x = range(mtcars$wt), y = range(mtcars$mpg)), 
    aes(x, y), inherit.aes = FALSE
    ) +
  coord_cartesian(clip="off") +
  theme_tufte() +
  facet_wrap(~am)

## Arguably looks better if we use scales = 'free_y' to plot the y-axis
## labels in the RHS facet
p + 
  geom_rangeframe(
    data = data.frame(x = range(mtcars$wt), y = range(mtcars$mpg)), 
    aes(x, y), 
    inherit.aes = FALSE
    ) +
  coord_cartesian(clip="off") +
  theme_tufte() +
  facet_wrap(~am, scales = 'free_y')

Created on 2021-09-08 by the reprex package (v2.0.1)

albert-ying commented 2 years ago

Thank you so much!

This example only works with a fixed scale, and the axis number looks strange.

To anyone like this style, I wrote a package just for this https://github.com/albert-ying/ggRetro Feel free to check it out.