I can't use theme_set() with theme_xkcd() in r-markdown document

Does any one have tried set theme_xkcd() globally? I'm getting this error and I dont know how to solve it.

library(ggplot2)
library(xkcd)
#> Loading required package: extrafont
#> Registering fonts with R
library(magrittr)

theme_set(
    theme_xkcd()
) 
#> Warning: New theme missing the following elements: line, rect,
#> axis.title.x, axis.title.x.top, axis.title.y, axis.title.y.right,
#> axis.text, axis.text.x, axis.text.x.top, axis.text.y, axis.text.y.right,
#> axis.ticks.length, axis.line, axis.line.x, axis.line.y, legend.background,
#> legend.margin, legend.spacing, legend.spacing.x, legend.spacing.y,
#> legend.key.size, legend.key.height, legend.key.width, legend.text,
#> legend.text.align, legend.title, legend.title.align, legend.position,
#> legend.direction, legend.justification, legend.box, legend.box.margin,
#> legend.box.background, legend.box.spacing, panel.border, panel.spacing,
#> panel.spacing.x, panel.spacing.y, panel.grid, panel.ontop, plot.background,
#> plot.title, plot.subtitle, plot.caption, plot.tag, plot.tag.position,
#> plot.margin, strip.placement, strip.text, strip.text.x, strip.text.y,
#> strip.switch.pad.grid, strip.switch.pad.wrap
cars %>% 
    ggplot(aes(speed, dist)) +
    geom_point()
#> Theme element panel.border missing
#> Error in Ops.unit(one, theme$axis.ticks.length): both operands must be units

Created on 2018-08-14 by the reprex package (v0.2.0).

Unfortunately, it looks like xkcd hasn't been updated in 5 years, so it won't work with ggplot2 out of the box. You can try getting some of the parts out of the package manually, of course.

Yeah, I noticed missing magrittr error too, so checked if xkcd works with current version of ggplot2 and unfortunately it doesn't.

Yeah, that was just a blooper, I forgot that I have loaded dplyr in my interactive session, I have edited my reprex to show the actual error.

Nevertheless, theme_xkcd() works just fine if I don't set it globally, as you can see in this new reprex, thats why I think there must be a walk around solution for this, but I don't have that much practice customising ggplot2 themes.

library(ggplot2)
library(xkcd)
#> Loading required package: extrafont
#> Registering fonts with R
library(magrittr)

cars %>% 
    ggplot(aes(speed, dist)) +
    geom_point() + 
    theme_xkcd()

Created on 2018-08-14 by the reprex package (v0.2.0).

1 Like

A possible work-around is to use a theme that has all the required elements as the "base" and then add all the theme_xkcd() elements to it. I'll use theme_grey() for this.

(I don't have the xkcd fonts installed, so the axis font doesn't change in my example.)

library(ggplot2)
library(xkcd)

theme_set(theme_grey() + theme_xkcd() ) 

ggplot(cars, aes(speed, dist)) +
     geom_point()

Created on 2018-08-14 by the reprex package (v0.2.0).

5 Likes

@aosmith That was helpful, thank you a lot!