😎 Give your xaringan slides some style
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

383 lines
13KB

  1. ---
  2. title: "ggplot2 Themes"
  3. output: rmarkdown::html_vignette
  4. vignette: >
  5. %\VignetteIndexEntry{ggplot2 Themes}
  6. %\VignetteEngine{knitr::rmarkdown}
  7. %\VignetteEncoding{UTF-8}
  8. ---
  9. ```{r, include = FALSE}
  10. knitr::opts_chunk$set(
  11. collapse = TRUE,
  12. warning = FALSE,
  13. comment = "#>",
  14. fig.width = 6,
  15. fig.height = 4
  16. )
  17. ```
  18. ```{css echo=FALSE}
  19. img { max-width: 100%; border: none; }
  20. ```
  21. **xaringanthemer** provides two [ggplot2] themes for your [xaringan] slides
  22. to help your data visualizations blend seamlessly into your slides.
  23. Use `theme_xaringan()` to create plots that match your primary slide style
  24. or `theme_xaringan_inverse()` to match the style of your inverse slides.
  25. <img src="https://raw.githubusercontent.com/gadenbuie/xaringanthemer/assets/theme-xaringan-inverse.png" alt="Examples slides with ggplot2 plots that match the xaringanthemer theme" data-external="1" />
  26. ### Key Features
  27. - The ggplot2 themes [uses the colors and themes](#setup-your-theme) from the **xaringanthemer** style functions, if you set your theme inside your slides. Otherwise, it [draws from the `xaringan-themer.css` file](#using-xaringan-themer-css).
  28. - The themes [pick appropriate colors](#colors) for titles, grid lines, and axis text,
  29. and also sets the default colors of geoms like `ggplot2::geom_point()` and
  30. `ggplot2::geom_text()`. There are also monotone
  31. [color and fill scales](#scale-xaringan) based around the primary accent color
  32. used in your xaringan theme.
  33. - If you use Google Fonts in your slides, the ggplot2 themes use the showtext
  34. package to [automatically match the title and axis text fonts](#fonts)
  35. of your plots to the heading and text fonts in your xaringan theme.
  36. <!--
  37. - I've done my best to set up everything so that _it just works_, but sometimes
  38. the showtext package adds a bit of complication to the routine data
  39. visualization workflow. At the end of this vignette I include
  40. [a few tips](#tips) for working with showtext.
  41. -->
  42. ## Setup Your Theme
  43. `theme_xaringan()` is designed to automatically use
  44. the fonts and colors you used for your slides' style theme.
  45. Here I'm going to use a moderately customized color theme
  46. based on `style_mono_accent()`,
  47. that results in the xaringan theme previewed in the slides above.
  48. I've also picked out a few fonts from [Google Fonts][google-fonts]
  49. that I would probably never use in a real presentation,
  50. but they're flashy enough to make it easy to see
  51. that we're not using the standard default fonts.
  52. ````markdown
  53. ```{r xaringan-themer, include=FALSE}`r ''`
  54. library(xaringanthemer)
  55. style_mono_accent(
  56. base_color = "#DC322F", # bright red
  57. inverse_background_color = "#002B36", # dark dark blue
  58. inverse_header_color = "#31b09e", # light aqua green
  59. inverse_text_color = "#FFFFFF", # white
  60. title_slide_background_color = "var(--base)",
  61. text_font_google = google_font("Kelly Slab"),
  62. header_font_google = google_font("Oleo Script")
  63. )
  64. ```
  65. ````
  66. ```{r setup, include=FALSE}
  67. library(xaringanthemer)
  68. style_mono_accent(
  69. base_color = "#DC322F",
  70. inverse_background_color = "#002B36",
  71. inverse_header_color = "#31b09e",
  72. inverse_text_color = "#FFFFFF",
  73. title_slide_background_color = "var(--base)",
  74. text_font_google = google_font("Kelly Slab"),
  75. header_font_google = google_font("Oleo Script"),
  76. outfile = NULL
  77. )
  78. ```
  79. If you use a hidden chunk like this one
  80. inside your slides' R Markdown source file,
  81. `theme_xaringan()` will know which colors and fonts you've picked.
  82. Adding `theme_xaringan()` to a ggplot,
  83. like this demonstration plot using the `mpg` dataset from ggplot2,
  84. changes the colors and fonts of your plot theme.
  85. ```{r ggplot2-demo-1, out.width = "45%", fig.show="hide"}
  86. library(ggplot2)
  87. g_base <- ggplot(mpg) +
  88. aes(hwy, cty) +
  89. geom_point() +
  90. labs(x = "Highway MPG", y = "City MPG", title = "Fuel Efficiency")
  91. # Basic plot with default theme
  92. g_base
  93. ```
  94. ```{r ggplot2-demo-2, fig.show="hide"}
  95. # Fancy slide-matching themed plot
  96. g_base + theme_xaringan()
  97. ```
  98. <img src="`r knitr::fig_chunk("ggplot2-demo-1", "png")`" width="45%" /><img src="`r knitr::fig_chunk("ggplot2-demo-2", "png")`" width="45%" />
  99. With `theme_xaringan()` the fonts and colors match the slide theme.
  100. The default colors of points (like other geometries) has been changed as well
  101. to match the slide colors.
  102. To restore the previous default colors of ggplot2 geoms, call
  103. ```{r eval=FALSE}
  104. theme_xaringan_restore_defaults()
  105. ```
  106. Add `theme_xaringan_inverse()` to automatically create a plot
  107. that matches the inverse slide style.
  108. ```{r ggplot2-demo-inverse, fig.show="hide"}
  109. # theme_xaringan() on the left, theme_xaringan_inverse() on the right
  110. g_base + theme_xaringan_inverse()
  111. ```
  112. <img src="`r knitr::fig_chunk("ggplot2-demo-2", "png")`" width="45%" /><img src="`r knitr::fig_chunk("ggplot2-demo-inverse", "png")`" width="45%" />
  113. ## Using `theme_xaringan()` without calling a style function {#using-xaringan-themer-css}
  114. Once you've set up your custom xaringan theme,
  115. you might want to use the theme's CSS file for new presentations
  116. instead of rebuilding your theme with every new slide deck.
  117. In these cases, `theme_xaringan()` will look for a CSS file
  118. written by **xaringanthemer** in your slides' directory
  119. or in a subfolder under the same directory
  120. that it can use to determine the colors and fonts used in your slides.
  121. If you happen to have multiple slide themes
  122. written by **xaringanthemer** in the same directory,
  123. the one named `xaringan-themer.css` will be used.
  124. If xaringanthemer picks the wrong file,
  125. you can use the `css_file` in `theme_xaringan()`
  126. to specify exactly which CSS file to use.
  127. ```{r eval=FALSE}
  128. theme_xaringan(css_file = "my-slide-style.css")
  129. ```
  130. Note that you can use `theme_xaringan()` anywhere you want,
  131. not just in xaringan slides!
  132. (For example, `theme_xaringan()` is working great in these vignettes!)
  133. This means that you can use your plot theme in reports and websites
  134. while maintaining a consistent look and feel or brand.
  135. Finally, you don't even need a xaringanthemer CSS file.
  136. You can specify the key ingredients for the theme
  137. as arguments to `theme_xaringan()`, namely
  138. text, background, and accent colors as well as text and title fonts.
  139. The R chunk below replicated the demonstrated theme,
  140. but doesn't require a slide style to be set or stored in a CSS file.
  141. ```{r eval=FALSE}
  142. theme_xaringan(
  143. text_color = "#3D3E38",
  144. background_color = "#FFFFFF",
  145. accent_color = "#DC322F",
  146. text_font = "Kelly Slab",
  147. text_font_use_google = TRUE,
  148. title_font = "Oleo Script",
  149. title_font_use_google = TRUE
  150. )
  151. ```
  152. ## Colors
  153. As demonstrated above,
  154. `theme_xaringan()` and `theme_xaringan_inverse()`
  155. modify the default colors and fonts of geometries.
  156. This means that `geom_point()`, `geom_bar()`, `geom_text()`
  157. and other geoms used in your plots
  158. will reasonably match your slide themes with no extra work.
  159. ```{r demo-geom-defaults, fig.width = 10}
  160. g_diamonds <- ggplot(diamonds, aes(x = cut)) +
  161. geom_bar() +
  162. labs(x = NULL, y = NULL, title = "Diamond Cut Quality") +
  163. ylim(0, 25000)
  164. g_diamonds + theme_xaringan()
  165. ```
  166. Whenever `theme_xaringan()` or `theme_xaringan_inverse()` are called,
  167. the default values of many of ggplot2 geoms are set by default.
  168. You can opt out of this by setting `set_ggplot_defaults = FALSE`
  169. when using either theme.
  170. You can also restore the geom aesthetic defaults to their original values
  171. before the first time `theme_xaringan()` or `theme_xaringan_inverse()`
  172. were used by running
  173. ```{r eval=FALSE}
  174. theme_xaringan_restore_defaults()
  175. ```
  176. ### Custom Color and Fill Scales {#scale-xaringan}
  177. xaringanthemer includes monotone color and fill scales
  178. to match your ggplot2 theme.
  179. The scale functions all follow the naming pattern
  180. `scale_xaringan_<aes>_<data_type>()`,
  181. where `<aes>` is replaced with either `color` or `fill`
  182. and `<data_type>` is one of `discrete` or `continuous`.
  183. These scales use `colorspace::sequential_hcl()`
  184. to create a sequential, monotone color scale
  185. based on the primary accent color in your slides.
  186. Color scales matching the inverse slides are possible
  187. by setting the argument `inverse = TRUE`.
  188. ```{r scale-xaringan, fig.width = 9, fig.height = 5, out.width="45%", fig.show="hold", echo = TRUE}
  189. ggplot(diamonds, aes(x = cut)) +
  190. geom_bar(aes(fill = ..count..), show.legend = FALSE) +
  191. labs(x = NULL, y = "Count", title = "Diamond Cut Quality") +
  192. theme_xaringan() +
  193. scale_xaringan_fill_continuous()
  194. ggplot(mpg, aes(x = hwy, y = cty)) +
  195. geom_count(aes(color = ..n..), show.legend = FALSE) +
  196. labs(x = "Highway MPG", y = "City MPG", title = "Fuel Efficiency") +
  197. theme_xaringan_inverse() +
  198. scale_xaringan_color_continuous(breaks = seq(3, 12, 2), inverse = TRUE, begin = 1, end = 0)
  199. ```
  200. In general, these color scales aren't great
  201. at representing the underlying data.
  202. In both examples above,
  203. the color and fill scales duplicate information displayed via other aesthetics
  204. (the height of the bar or the size of the point).
  205. I recommend using these scales primarily for style,
  206. although the scales can be more or less effective
  207. depending on your color scheme.
  208. The scales come with a few more options:
  209. - Choose a different primary color using the `color` argument.
  210. - Use the inverse color slide theme color with `inverse = TRUE`
  211. (only applies when `color` is not supplied).
  212. - Invert the direction of the discrete scales with `direction = -1`.
  213. - Control the range of the continuous color scale used with `begin` and `end`.
  214. You can also invert the direction of the continous color scale by setting
  215. `begin = 1` and `end = 0`.
  216. ## Fonts
  217. ### Automatically match slide and plot fonts
  218. xaringanthemer uses the [showtext] and [sysfonts] packages by Yixuan Qiu
  219. to automatically download and register [Google Fonts][google-fonts]
  220. for use with your ggplot2 plots.
  221. In your slide theme,
  222. use the `<type>_font_google` argument
  223. with the `google_font("<font name>")` helper
  224. (or the default xaringanthemer fonts)
  225. and `theme_xaringan()` will handle the rest.
  226. In our demo theme, we used `style_mono_accent()` with
  227. - `text_font_google = google_font("Kelley Slab")` and
  228. - `header_font_google = google_font("Oleo Script")`.
  229. ```{r text demo, fig.width = 10}
  230. g_diamonds_with_text <-
  231. g_diamonds +
  232. geom_text(aes(y = ..count.., label = format(..count.., big.mark = ",")),
  233. vjust = -0.30, size = 8, stat = "count") +
  234. labs(x = "Cut", y = "Count")
  235. g_diamonds_with_text + theme_xaringan()
  236. ```
  237. `theme_xaringan()` applies the header font to the plot and axis titles
  238. and the text font to the axis ticks labels and any text geoms or annotations.
  239. ### Manually specify plot fonts
  240. You can also specify specific fonts for your plot theme.
  241. Both `text_font` and `title_font` in `theme_xaringan()` and `theme_xaringan_inverse()`
  242. accept `google_font()`s directly.
  243. ```{r text-demo-2, fig.width = 10}
  244. g_diamonds_with_text +
  245. theme_xaringan(
  246. text_font = google_font("Ranga"),
  247. title_font = google_font("Holtwood One SC")
  248. )
  249. ```
  250. ### Using fonts not in Google Fonts
  251. If you want to use a font that isn't in the Google Fonts collection,
  252. you need to manually register the font with sysfonts
  253. so that it can be used in your plots.
  254. I found a nice open source font called
  255. [Glacial Indifference](https://fontlibrary.org/en/font/glacial-indifference)
  256. by Alfredo Marco Pradil
  257. avilable at [fontlibrary.org](https://fontlibrary.org).
  258. In my theme style function,
  259. I would use
  260. ```
  261. style_mono_accent(
  262. text_font_family = "GlacialIndifferenceRegular",
  263. text_font_url = "https://fontlibrary.org/face/glacial-indifference"
  264. )
  265. ```
  266. but sysfonts won't know where to find the TTF font files for this font.
  267. To register the font with sysfont, we use `sysfonts::font_add()`,
  268. but first we need to download the font file —
  269. the `sysfonts::font_add()` function requires the font file to be local.
  270. By inspecting the CSS file at the link I used in `text_font_url`,
  271. I found a direct URL for the `.ttf` files for _GlacialIndifferenceRegular_.
  272. I've included the code I used to download the font to a temporary file below,
  273. but in case the URL breaks, I've included _Glacial Indifference_
  274. in the xaringanthemer package.
  275. ```{r eval=FALSE}
  276. font_url <- file.path(
  277. "https://fontlibrary.org/assets/fonts/glacial-indifference",
  278. "5f2cf277506e19ec77729122f27b1faf/0820b3c58fed35de298219f314635982",
  279. "GlacialIndifferenceRegular.ttf"
  280. )
  281. font_temp <- tempfile()
  282. download.file(font_url, font_temp)
  283. ```
  284. ```{r sysfonts-custom-font, fig.width = 10}
  285. # Path to the local custom font file
  286. font_temp <- system.file(
  287. "fonts/GlacialIndifferenceRegular.ttf", package = "xaringanthemer"
  288. )
  289. # Register the font with sysfonts/showtext
  290. sysfonts::font_add(family = "GlacialIndifferenceRegular", regular = font_temp)
  291. # Now it's available for use!
  292. g_diamonds_with_text +
  293. theme_xaringan(
  294. text_font = "GlacialIndifferenceRegular",
  295. title_font = "GlacialIndifferenceRegular"
  296. )
  297. ```
  298. <!-- ## Tips for using the showtext package {#tips} -->
  299. [ggplot2]: https://ggplot2.tidyverse.org
  300. [xaringan]: https://github.com/yihui/xaringan
  301. [google-fonts]: https://fonts.google.com
  302. [showtext]: https://github.com/yixuan/showtext
  303. [sysfonts]: https://github.com/yixuan/sysfonts