wilkelab / ggtext

Improved text rendering support for ggplot2
https://wilkelab.org/ggtext/
GNU General Public License v2.0
650 stars 37 forks source link

Error with image rendering in facet labels #78

Closed CamBullen closed 2 years ago

CamBullen commented 2 years ago

Really enjoying ggtext for adding images to plots, however I have come across a couple bugs (I think) when using images in facet labels.

  1. Images do not appear when using the "switch" option on y facets but works fine on x facets.
  2. When specifying element_markdown for facets in theme call, images do not appear for y facets unless strip.text.y is used (strip.text.y does not seem to inherit from strip.text). Again, this is not an issue for x facets.

Examples of the issues are given below.

I'm guessing these behaviours are indicative of an issue, but it's also possible the error is on my end. It could also be the case that the root issues are in the labeller() or as_labeller() functions in ggplot2, but I thought I would start here.


library(ggtext)
library(ggplot2)

# Define labels
labels <- c(
  # Image labels for number of gears variable
  `3` = "<img src='3NumberThreeInCircle_whitebackground.png' width='20'/>",
  `4` = "<img src='4_icon.png' width='20'/>",
  `5` = "<img src='Calendar_Icon_5_RW.png' width='20'/>", 
  # text labels for am variable
  `0` = "0",
  `1` = "1"
    )

# plot without switching facet sides, works fine
ggplot(mtcars, aes(mpg, hp)) +
  geom_point() +
  facet_grid(gear ~ am,
             labeller = as_labeller(labels))+
  theme(strip.text.y = element_markdown(colour = "red"))

image

# plot with switching facet sides, images don't work
ggplot(mtcars, aes(mpg, hp)) +
  geom_point() +
  facet_grid(gear ~ am,
             labeller = as_labeller(labels),
             switch = "both")+
  theme(strip.text.y = element_markdown(colour = "red"))

image

# Issue does not occur with x facets (am and gear swapped in facet call)
ggplot(mtcars, aes(mpg, hp)) +
  geom_point() +
  facet_grid(am ~ gear,
             labeller = as_labeller(labels),
             switch = "both")+
  theme(strip.text = element_markdown(colour = "red"))

image


# Second (possibly related) issue, images do not appear in y strip text unless strip text.y is used in theme.
  # i.e. strip.text.y does not appear to inherit from strip.text
ggplot(mtcars, aes(mpg, hp)) +
  geom_point() +
  facet_grid(gear ~ am,
             labeller = as_labeller(labels))+
  theme(strip.text = element_markdown(colour = "red"))

Note that interestingly the text colour specified in element_markdown is applied, but the images are not produced.

image

clauswilke commented 2 years ago

That's how ggplot2 themes work. Please read up on ggplot2 theme inheritance.

https://www.rstudio.com/resources/rstudioglobal-2021/always-look-on-the-bright-side-of-plots/