😎 Give your xaringan slides some style
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

1033 lines
32KB

  1. #' A Plot Theme for ggplot2 by xaringanthemer
  2. #'
  3. #' @description
  4. #'
  5. #' **Lifecycle:** [Maturing](https://www.tidyverse.org/lifecycle/#maturing)
  6. #'
  7. #' Creates \pkg{ggplot2} themes to match the xaringanthemer theme used in the
  8. #' \pkg{xaringan} slides that seamlessly matches the "normal" slide colors and
  9. #' styles. See `vignette("ggplot2-themes")` for more information and examples.
  10. #'
  11. #' @param text_color Color for text and foreground, inherits from `text_color`
  12. #' @param background_color Color for background, inherits from
  13. #' `background_color`
  14. #' @param accent_color Color for titles and accents, inherits from
  15. #' `header_color`
  16. #' @param accent_secondary_color Color for secondary accents, inherits from
  17. #' `text_bold_color`
  18. #' @param css_file Path to a \pkg{xaringanthemer} CSS file, from which the
  19. #' theme variables and values will be inferred. In general, if you use the
  20. #' \pkg{xaringathemer} defaults, you will not need to set this. This feature
  21. #' lets you create a \pkg{ggplot2} theme for your \pkg{xaringan} slides, even
  22. #' if you have only saved your theme CSS file and you aren't creating your
  23. #' CSS theme with \pkg{xaringanthemer} in your slides' source file.
  24. #' @inheritParams theme_xaringan_base
  25. #'
  26. #' @examples
  27. #' # Requires ggplot2
  28. #' has_ggplot2 <- requireNamespace("ggplot2", quietly = TRUE)
  29. #'
  30. #' if (has_ggplot2) {
  31. #' # Because this is an example, we'll save the CSS to a temp file
  32. #' path_to_css_file <- tempfile(fileext = ".css")
  33. #'
  34. #' # Create the xaringan theme: dark blue background with teal green accents
  35. #' style_duo(
  36. #' primary_color = "#002b36",
  37. #' secondary_color = "#31b09e",
  38. #' # Using basic fonts for this example, but the plot theme will
  39. #' # automatically use your theme font if you use Google fonts
  40. #' text_font_family = "sans",
  41. #' header_font_family = "serif",
  42. #' outfile = path_to_css_file
  43. #' )
  44. #'
  45. #' library(ggplot2)
  46. #' ggplot(iris) +
  47. #' aes(Petal.Length, Petal.Width) +
  48. #' geom_point() +
  49. #' ggtitle("Yet another Iris plot") +
  50. #' theme_xaringan()
  51. #' }
  52. #' @return A ggplot2 theme
  53. #' @family xaringanthemer ggplot2 themes
  54. #' @export
  55. theme_xaringan <- function(
  56. text_color = NULL,
  57. background_color = NULL,
  58. accent_color = NULL,
  59. accent_secondary_color = NULL,
  60. css_file = NULL,
  61. set_ggplot_defaults = TRUE,
  62. text_font = NULL,
  63. text_font_use_google = NULL,
  64. text_font_size = NULL,
  65. title_font = NULL,
  66. title_font_use_google = NULL,
  67. title_font_size = NULL,
  68. use_showtext = TRUE
  69. ) {
  70. requires_xaringanthemer_env(css_file = css_file, try_css = TRUE)
  71. requires_package(fn = "xaringan_theme")
  72. background_color <- background_color %||% xaringanthemer_env$background_color
  73. text_color <- text_color %||% xaringanthemer_env$text_color
  74. accent_color <- accent_color %||% xaringanthemer_env$header_color
  75. accent_secondary_color <- accent_secondary_color %||% xaringanthemer_env$text_bold_color %||% accent_color
  76. theme_xaringan_base(
  77. text_color,
  78. background_color,
  79. accent_color = accent_color,
  80. accent_secondary_color = accent_secondary_color,
  81. set_ggplot_defaults = set_ggplot_defaults,
  82. text_font = text_font,
  83. text_font_use_google = text_font_use_google,
  84. text_font_size = text_font_size,
  85. title_font = title_font,
  86. title_font_use_google = title_font_use_google,
  87. title_font_size = title_font_size,
  88. use_showtext = use_showtext
  89. )
  90. }
  91. #' An Inverse Plot Theme for ggplot2 by xaringanthemer
  92. #'
  93. #' @description
  94. #'
  95. #' **Lifecycle:** [Maturing](https://www.tidyverse.org/lifecycle/#maturing)
  96. #'
  97. #' A \pkg{ggplot2} xaringanthemer plot theme to seamlessly match the "inverse"
  98. #' \pkg{xaringan} slide colors and styles as styled by [xaringanthemer]. See
  99. #' `vignette("ggplot2-themes")` for more information and examples.
  100. #'
  101. #' @param text_color Color for text and foreground, inherits from `text_color`
  102. #' @param background_color Color for background, inherits from
  103. #' `background_color`
  104. #' @param accent_color Color for titles and accents, inherits from
  105. #' `header_color`
  106. #' @param accent_secondary_color Color for secondary accents, inherits from
  107. #' `text_bold_color`
  108. #' @inheritParams theme_xaringan
  109. #' @inheritParams theme_xaringan_base
  110. #'
  111. #' @examples
  112. #' # Requires ggplot2
  113. #' has_ggplot2 <- requireNamespace("ggplot2", quietly = TRUE)
  114. #'
  115. #' if (has_ggplot2) {
  116. #' # Because this is an example, we'll save the CSS to a temp file
  117. #' path_to_css_file <- tempfile(fileext = ".css")
  118. #'
  119. #' # Create the xaringan theme: dark blue background with teal green accents
  120. #' style_duo(
  121. #' primary_color = "#002b36",
  122. #' secondary_color = "#31b09e",
  123. #' # Using basic fonts for this example, but the plot theme will
  124. #' # automatically use your theme font if you use Google fonts
  125. #' text_font_family = "sans",
  126. #' header_font_family = "serif",
  127. #' outfile = path_to_css_file
  128. #' )
  129. #'
  130. #' library(ggplot2)
  131. #' ggplot(iris) +
  132. #' aes(Petal.Length, Petal.Width) +
  133. #' geom_point() +
  134. #' ggtitle("Yet another Iris plot") +
  135. #' # themed to match the inverse slides: teal background with dark blue text
  136. #' theme_xaringan_inverse()
  137. #' }
  138. #' @return A ggplot2 theme
  139. #' @family xaringanthemer ggplot2 themes
  140. #' @export
  141. theme_xaringan_inverse <- function(
  142. text_color = NULL,
  143. background_color = NULL,
  144. accent_color = NULL,
  145. accent_secondary_color = NULL,
  146. css_file = NULL,
  147. set_ggplot_defaults = TRUE,
  148. text_font = NULL,
  149. text_font_use_google = NULL,
  150. text_font_size = NULL,
  151. title_font = NULL,
  152. title_font_use_google = NULL,
  153. title_font_size = NULL,
  154. use_showtext = TRUE
  155. ) {
  156. requires_xaringanthemer_env(css_file = css_file, try_css = TRUE)
  157. requires_package(fn = "xaringan_theme")
  158. background_color <- background_color %||% xaringanthemer_env$inverse_background_color
  159. text_color <- text_color %||% xaringanthemer_env$inverse_text_color
  160. accent_color <- accent_color %||% xaringanthemer_env$inverse_header_color
  161. accent_secondary_color <- accent_secondary_color %||% accent_color
  162. theme_xaringan_base(
  163. text_color,
  164. background_color,
  165. accent_color = accent_color,
  166. accent_secondary_color = accent_secondary_color,
  167. set_ggplot_defaults = set_ggplot_defaults,
  168. text_font = text_font,
  169. text_font_use_google = text_font_use_google,
  170. text_font_size = text_font_size,
  171. title_font = title_font,
  172. title_font_use_google = title_font_use_google,
  173. title_font_size = title_font_size,
  174. use_showtext = use_showtext
  175. )
  176. }
  177. #' The ggplot2 xaringanthemer base plot theme
  178. #'
  179. #' @description
  180. #'
  181. #' **Lifecycle:** [Maturing](https://www.tidyverse.org/lifecycle/#maturing)
  182. #'
  183. #' Provides a base plot theme for \pkg{ggplot2} to match the \pkg{xaringan}
  184. #' slide theme created by [xaringanthemer]. The theme is designed to create a
  185. #' general plot style from two colors, a `background_color` and a `text_color`
  186. #' (or foreground color). Also accepts an `accent_color` and an
  187. #' `accent_secondary_color` that are [xaringanthemer] is not required for the
  188. #' base theme. Use [theme_xaringan()] or [theme_xaringan_inverse()] in xaringan
  189. #' slides styled by xaringanthemer for a plot theme that matches the slide
  190. #' style. See `vignette("ggplot2-themes")` for more information and examples.
  191. #'
  192. #' @param text_color Color for text and foreground
  193. #' @param background_color Color for background
  194. #' @param accent_color Color for titles and accents, inherits from
  195. #' `header_color` or `text_color`. Used for the `title` base setting in
  196. #' [ggplot2::theme()], and additionally for setting the `color` or `fill` of
  197. #' \pkg{ggplot2} geom defaults.
  198. #' @param accent_secondary_color Color for secondary accents, inherits from
  199. #' `text_bold_color` or `accent_color`. Used only when setting \pkg{ggplot2} geom
  200. #' defaults.
  201. #' @param set_ggplot_defaults Should defaults be set for \pkg{ggplot2} _geoms_?
  202. #' Defaults to TRUE. To restore ggplot's defaults, or the previously set geom
  203. #' defaults, see [theme_xaringan_restore_defaults()].
  204. #' @param text_font Font to use for text elements, passed to
  205. #' [sysfonts::font_add_google()], if available and `text_font_use_google` is
  206. #' `TRUE`. Inherits from `text_font_family`. If manually specified, can be a
  207. #' [google_font()].
  208. #' @param text_font_use_google Is `text_font` available on [Google
  209. #' Fonts](https://fonts.google.com)?
  210. #' @param text_font_size Base text font size, inherits from `text_font_size`, or
  211. #' defaults to 11.
  212. #' @param title_font Font to use for title elements, passed to
  213. #' [sysfonts::font_add_google()], if available and `title_font_use_google` is
  214. #' `TRUE`. Inherits from `title_font_family`. If manually specified, can be a
  215. #' [google_font()].
  216. #' @param title_font_use_google Is `title_font` available on [Google
  217. #' Fonts](https://fonts.google.com)?
  218. #' @param title_font_size Base text font size, inherits from `title_font_size`,
  219. #' or defaults to 14.
  220. #' @param use_showtext If `TRUE` (default) the \pkg{showtext} package will be
  221. #' used to register Google fonts. Set to `FALSE` to disable this feature
  222. #' entirely, which may result in errors during plotting if the fonts used are
  223. #' not available locally.
  224. #' @param ... Ignored
  225. #'
  226. #' @examples
  227. #' # Requires ggplot2
  228. #' has_ggplot2 <- requireNamespace("ggplot2", quietly = TRUE)
  229. #'
  230. #' if (has_ggplot2) {
  231. #' library(ggplot2)
  232. #'
  233. #' plot1 <- ggplot(iris) +
  234. #' aes(Petal.Length, Petal.Width) +
  235. #' geom_point() +
  236. #' theme_xaringan_base(
  237. #' text_color = "#602f6b", # imperial
  238. #' background_color = "#f8f8f8", # light gray
  239. #' accent_color = "#317873", # myrtle green
  240. #' title_font = "sans",
  241. #' text_font = "serif",
  242. #' set_ggplot_defaults = TRUE
  243. #' ) +
  244. #' labs(
  245. #' title = "Basic Iris Plot",
  246. #' subtitle = "+ theme_xaringan_base()",
  247. #' caption = "xaringanthemer"
  248. #' )
  249. #'
  250. #' print(plot1)
  251. #'
  252. #' plot2 <- ggplot(iris) +
  253. #' aes(Sepal.Width) +
  254. #' geom_histogram(binwidth = 0.1) +
  255. #' theme_xaringan_base(
  256. #' text_color = "#a8a9c8", # light purple
  257. #' background_color = "#303163", # deep slate purple
  258. #' accent_color = "#ffff99", # canary yellow
  259. #' title_font = "sans",
  260. #' text_font = "serif",
  261. #' set_ggplot_defaults = TRUE
  262. #' ) +
  263. #' labs(
  264. #' title = "Basic Iris Plot",
  265. #' subtitle = "+ theme_xaringan_base()",
  266. #' caption = "xaringanthemer"
  267. #' )
  268. #'
  269. #' print(plot2)
  270. #' }
  271. #' @return A ggplot2 theme
  272. #' @family xaringanthemer ggplot2 themes
  273. #' @export
  274. theme_xaringan_base <- function(
  275. text_color,
  276. background_color,
  277. ...,
  278. set_ggplot_defaults = TRUE,
  279. accent_color = NULL,
  280. accent_secondary_color = NULL,
  281. text_font = NULL,
  282. text_font_use_google = NULL,
  283. text_font_size = NULL,
  284. title_font = NULL,
  285. title_font_use_google = NULL,
  286. title_font_size = NULL,
  287. use_showtext = TRUE
  288. ) {
  289. text_color <- full_length_hex(text_color)
  290. background_color <- full_length_hex(background_color)
  291. blend <- color_blender(text_color, background_color)
  292. text_font_size <- text_font_size %||% web_to_point(xaringanthemer_env$text_font_size, scale = 1.25) %||% 11
  293. title_font_size <- title_font_size %||% web_to_point(xaringanthemer_env$header_h3_font_size, scale = 0.8) %||% 14
  294. text_font_use_google <- text_font_use_google %||% is_google_font(text_font)
  295. title_font_use_google <- title_font_use_google %||% is_google_font(title_font)
  296. text_font <- if (!is.null(text_font)) {
  297. register_font(text_font, identical(text_font_use_google, TRUE) && use_showtext)
  298. } else {
  299. get_theme_font("text")
  300. }
  301. title_font <- if (!is.null(title_font)) {
  302. register_font(title_font, identical(title_font_use_google, TRUE) && use_showtext)
  303. } else {
  304. get_theme_font("header")
  305. }
  306. text_font <- text_font %||% "sans"
  307. title_font <- title_font %||% "sans"
  308. if (set_ggplot_defaults) {
  309. accent_color <- accent_color %||% xaringanthemer_env$header_color %||% text_color
  310. accent_secondary_color <- accent_secondary_color %||% xaringanthemer_env$text_bold_color %||% accent_color
  311. accent_color <- full_length_hex(accent_color)
  312. accent_secondary_color <- full_length_hex(accent_secondary_color)
  313. theme_xaringan_set_defaults(
  314. text_color = text_color,
  315. background_color = background_color,
  316. accent_color = accent_color,
  317. accent_secondary_color = accent_secondary_color,
  318. text_font = text_font
  319. )
  320. }
  321. theme <- ggplot2::theme(
  322. line = ggplot2::element_line(color = blend(0.2)),
  323. rect = ggplot2::element_rect(fill = background_color),
  324. text = ggplot2::element_text(
  325. color = blend(0.1),
  326. family = text_font,
  327. size = text_font_size
  328. ),
  329. title = ggplot2::element_text(
  330. color = accent_color,
  331. family = title_font,
  332. size = title_font_size
  333. ),
  334. plot.background = ggplot2::element_rect(
  335. fill = background_color,
  336. color = background_color
  337. ),
  338. panel.background = ggplot2::element_rect(
  339. fill = background_color,
  340. color = background_color
  341. ),
  342. panel.grid.major = ggplot2::element_line(
  343. color = blend(0.8),
  344. inherit.blank = TRUE
  345. ),
  346. panel.grid.minor = ggplot2::element_line(
  347. color = blend(0.9),
  348. inherit.blank = TRUE
  349. ),
  350. axis.title = ggplot2::element_text(size = title_font_size * 0.8),
  351. axis.ticks = ggplot2::element_line(color = blend(0.8)),
  352. axis.text = ggplot2::element_text(color = blend(0.4)),
  353. legend.key = ggplot2::element_rect(fill = "transparent", colour = NA),
  354. plot.caption = ggplot2::element_text(
  355. size = text_font_size * 0.8,
  356. color = blend(0.3)
  357. )
  358. )
  359. if (utils::packageVersion("ggplot2") >= package_version("3.3.0")) {
  360. theme + ggplot2::theme(plot.title.position = "plot")
  361. } else theme
  362. }
  363. #' Set and Restore ggplot2 geom Defaults
  364. #'
  365. #' @description
  366. #'
  367. #' **Lifecycle:** [Maturing](https://www.tidyverse.org/lifecycle/#maturing)
  368. #'
  369. #' Set \pkg{ggplot2} _geom_ defaults to match [theme_xaringan()] with
  370. #' `theme_xaringan_set_defaults()` and restore the standard or previously-set
  371. #' defaults with `theme_xaringan_restore_defaults()`. By default,
  372. #' `theme_xaringan_set_defaults()` is run with [theme_xaringan()] or
  373. #' [theme_xaringan_inverse()].
  374. #'
  375. #' @family xaringanthemer ggplot2 themes
  376. #' @param text_font Font to use for text elements, passed to
  377. #' [sysfonts::font_add_google()], if available and `text_font_use_google` is
  378. #' `TRUE`. Inherits from `text_font_family`. Must be a length-one character.
  379. #' @inheritParams theme_xaringan
  380. #' @inheritParams theme_xaringan_base
  381. #' @return Invisibly returns a list of the current ggplot2 geom defaults
  382. #' @export
  383. theme_xaringan_set_defaults <- function(
  384. text_color = NULL,
  385. background_color = NULL,
  386. accent_color = text_color,
  387. accent_secondary_color = accent_color,
  388. text_font = NULL
  389. ) {
  390. requires_package("ggplot2")
  391. blend <- color_blender(text_color, background_color)
  392. xaringan_theme_defaults <- list(
  393. "line" = list(color = text_color),
  394. "vline" = list(color = accent_secondary_color),
  395. "hline" = list(color = accent_secondary_color),
  396. "abline" = list(color = accent_secondary_color),
  397. "segment" = list(color = text_color),
  398. "bar" = list(fill = accent_color),
  399. "col" = list(fill = accent_color),
  400. "boxplot" = list(color = text_color),
  401. "contour" = list(color = text_color),
  402. "density" = list(color = text_color,
  403. fill = text_color,
  404. alpha = 0.1),
  405. "dotplot" = list(color = accent_color),
  406. "errorbarh" = list(color = text_color),
  407. "crossbar" = list(color = text_color),
  408. "errorbar" = list(color = text_color),
  409. "linerange" = list(color = text_color),
  410. "pointrange" = list(color = text_color),
  411. "map" = list(color = text_color),
  412. "path" = list(color = text_color),
  413. "line" = list(color = text_color),
  414. "step" = list(color = text_color),
  415. "point" = list(color = accent_color),
  416. "polygon" = list(color = accent_color,
  417. fill = accent_color),
  418. "quantile" = list(color = text_color),
  419. "rug" = list(color = blend(0.5)),
  420. "segment" = list(color = text_color),
  421. "smooth" = list(fill = blend(0.75),
  422. color = accent_secondary_color),
  423. "spoke" = list(color = text_color),
  424. "label" = list(color = text_color,
  425. family= text_font %||% get_theme_font("text")),
  426. "text" = list(color = text_color,
  427. family= text_font %||% get_theme_font("text")),
  428. "rect" = list(fill = text_color),
  429. "tile" = list(fill = text_color),
  430. "violin" = list(fill = text_color),
  431. "sf" = list(color = text_color)
  432. )
  433. geom_names <- purrr::set_names(names(xaringan_theme_defaults))
  434. previous_defaults <- lapply(
  435. geom_names,
  436. function(geom) safely_set_geom(geom, xaringan_theme_defaults[[geom]])
  437. )
  438. if (is.null(xaringanthemer_env$old_ggplot_defaults)) {
  439. xaringanthemer_env$old_ggplot_defaults <- previous_defaults
  440. }
  441. invisible(previous_defaults)
  442. }
  443. #' @describeIn theme_xaringan_set_defaults Restore previous or standard
  444. #' \pkg{ggplot2} _geom_ defaults.
  445. #' @return Invisibly returns a list of the current ggplot2 geom defaults
  446. #' @export
  447. theme_xaringan_restore_defaults <- function() {
  448. requires_package("ggplot2")
  449. requires_xaringanthemer_env(try_css = FALSE, requires_theme = FALSE)
  450. if (is.null(xaringanthemer_env$old_ggplot_defaults)) {
  451. return(invisible())
  452. }
  453. old_default <- xaringanthemer_env$old_ggplot_defaults
  454. old_default_not_std <- vapply(old_default, function(x) length(x) > 0, logical(1))
  455. old_default <- old_default[old_default_not_std]
  456. restore_default <- utils::modifyList(xaringanthemer_env$std_ggplot_defaults, old_default)
  457. geom_names <- purrr::set_names(names(restore_default))
  458. previous_defaults <- lapply(
  459. geom_names,
  460. function(geom) safely_set_geom(geom, restore_default[[geom]])
  461. )
  462. invisible(previous_defaults)
  463. }
  464. safely_set_geom <- function(geom, new) {
  465. warn <- function(x) {
  466. warning(x$message, call. = TRUE, immediate. = TRUE)
  467. invisible()
  468. }
  469. tryCatch(
  470. {
  471. ggplot2::update_geom_defaults(geom, new)
  472. },
  473. error = warn,
  474. warning = warn
  475. )
  476. }
  477. # Color Scales ------------------------------------------------------------
  478. #' Themed ggplot2 Scales
  479. #'
  480. #' @description
  481. #'
  482. #' **Lifecycle:** [Maturing](https://www.tidyverse.org/lifecycle/#maturing)
  483. #'
  484. #' Color and fill single-color scales for discrete and continuous values,
  485. #' created using the primary accent color of the xaringanthemer styles. See
  486. #' `vignette("ggplot2-themes")` for more information and examples of
  487. #' \pkg{xaringanthemer}'s \pkg{ggplot2}-related functions.
  488. #'
  489. #' @param ... Arguments passed on to either the \pkg{colorspace} scale
  490. #' functions — one of [colorspace::scale_color_discrete_sequential()],
  491. #' [colorspace::scale_color_continuous_sequential()],
  492. #' [colorspace::scale_fill_discrete_sequential()], or
  493. #' [colorspace::scale_fill_continuous_sequential()] — or to
  494. #' [ggplot2::continuous_scale] or [ggplot2::discrete_scale].
  495. #' @param color A color value, in hex, to override the default color. Otherwise,
  496. #' the primary color of the resulting scale is chosen from the xaringanthemer
  497. #' slide styles.
  498. #' @param inverse If `color` is not supplied and `inverse = TRUE`, a primary
  499. #' color is chosen to work well with the inverse slide styles, namely the
  500. #' value of `inverse_header_color`
  501. #' @param direction Direction of the discrete scale. Use values less than 0 to
  502. #' reverse the direction, e.g. `direction = -1`.
  503. #' @inheritParams colorspace::scale_color_continuous_sequential
  504. #' @param aes_type The type of aesthetic to which the scale is being applied.
  505. #' One of "color", "colour", or "fill".
  506. #'
  507. #'
  508. #' @examples
  509. #' # Requires ggplot2
  510. #' has_ggplot2 <- requireNamespace("ggplot2", quietly = TRUE)
  511. #'
  512. #' if (has_ggplot2) {
  513. #' library(ggplot2)
  514. #' # Saving the theme to a temp file because this is an example
  515. #' path_to_css_file <- tempfile(fileext = ".css")
  516. #'
  517. #' # Create the xaringan theme: dark blue background with teal green accents
  518. #' style_duo(
  519. #' primary_color = "#002b36",
  520. #' secondary_color = "#31b09e",
  521. #' # Using basic fonts for this example, but the plot theme will
  522. #' # automatically use your theme font if you use Google fonts
  523. #' text_font_family = "sans",
  524. #' header_font_family = "serif",
  525. #' outfile = path_to_css_file
  526. #' )
  527. #'
  528. #' # Here's some very basic example data
  529. #' ex <- data.frame(
  530. #' name = c("Couple", "Few", "Lots", "Many"),
  531. #' n = c(2, 3, 5, 7)
  532. #' )
  533. #'
  534. #' # Fill color scales demo
  535. #' ggplot(ex) +
  536. #' aes(name, n, fill = n) +
  537. #' geom_col() +
  538. #' ggtitle("Matching fill scales") +
  539. #' # themed to match the slides: dark blue background with teal text
  540. #' theme_xaringan() +
  541. #' # Fill color matches teal text
  542. #' scale_xaringan_fill_continuous()
  543. #'
  544. #' # Color scales demo
  545. #' ggplot(ex) +
  546. #' aes(name, y = 1, color = name) +
  547. #' geom_point(size = 10) +
  548. #' ggtitle("Matching color scales") +
  549. #' # themed to match the slides: dark blue background with teal text
  550. #' theme_xaringan() +
  551. #' # Fill color matches teal text
  552. #' scale_xaringan_color_discrete(direction = -1)
  553. #' }
  554. #'
  555. #' @name scale_xaringan
  556. NULL
  557. #' @rdname scale_xaringan
  558. #' @export
  559. scale_xaringan_discrete <- function(
  560. aes_type = c("color", "colour", "fill"),
  561. ...,
  562. color = NULL,
  563. direction = 1,
  564. inverse = FALSE
  565. ) {
  566. requires_package("ggplot2", "scale_xaringan_discrete")
  567. aes_type <- match.arg(aes_type)
  568. color <- hex2HCL(get_theme_accent_color(color, inverse))
  569. pal <- function(n) {
  570. colors <- colorspace::sequential_hcl(
  571. n = n,
  572. c1 = color[1, "C"],
  573. l1 = color[1, "L"],
  574. h1 = color[1, "H"],
  575. rev = direction >= 1
  576. )
  577. }
  578. ggplot2::discrete_scale(aes_type, "manual", pal, ...)
  579. }
  580. #' @rdname scale_xaringan
  581. #' @export
  582. scale_xaringan_fill_discrete <- function(
  583. ...,
  584. color = NULL,
  585. direction = 1,
  586. inverse = FALSE
  587. ) {
  588. scale_xaringan_discrete(
  589. "fill",
  590. ...,
  591. color = color,
  592. direction = direction,
  593. inverse = inverse
  594. )
  595. }
  596. #' @rdname scale_xaringan
  597. #' @export
  598. scale_xaringan_color_discrete <- function(
  599. ...,
  600. color = NULL,
  601. direction = 1,
  602. inverse = FALSE
  603. ) {
  604. scale_xaringan_discrete(
  605. "color",
  606. ...,
  607. color = color,
  608. direction = direction,
  609. inverse = inverse
  610. )
  611. }
  612. #' @rdname scale_xaringan
  613. #' @export
  614. scale_xaringan_colour_discrete <- scale_xaringan_color_discrete
  615. #' @rdname scale_xaringan
  616. #' @export
  617. scale_xaringan_continuous <- function(
  618. aes_type = c("color", "colour", "fill"),
  619. ...,
  620. color = NULL,
  621. begin = 0,
  622. end = 1,
  623. inverse = FALSE
  624. ) {
  625. requires_package("ggplot2", "scale_xaringan_continuous")
  626. requires_package("scales", "scale_xaringan_continuous")
  627. aes_type <- match.arg(aes_type)
  628. color <- hex2HCL(get_theme_accent_color(color, inverse))
  629. colors <- suppressWarnings(colorspace::sequential_hcl(
  630. n = 12,
  631. c1 = color[1, "C"],
  632. l1 = color[1, "L"],
  633. h1 = color[1, "H"],
  634. rev = TRUE
  635. ))
  636. rescaler <- function(x, ...) {
  637. scales::rescale(x, to = c(begin, end), from = range(x, na.rm = TRUE))
  638. }
  639. ggplot2::continuous_scale(
  640. aes_type,
  641. "continuous_sequential",
  642. palette = scales::gradient_n_pal(colors, values = NULL),
  643. rescaler = rescaler,
  644. oob = scales::censor,
  645. ...
  646. )
  647. }
  648. #' @rdname scale_xaringan
  649. #' @export
  650. scale_xaringan_fill_continuous <- function(
  651. ...,
  652. color = NULL,
  653. begin = 0,
  654. end = 1,
  655. inverse = FALSE
  656. ) {
  657. scale_xaringan_continuous(
  658. "fill",
  659. ...,
  660. color = color,
  661. begin = begin,
  662. end = end,
  663. inverse = inverse
  664. )
  665. }
  666. #' @rdname scale_xaringan
  667. #' @export
  668. scale_xaringan_color_continuous <- function(
  669. ...,
  670. color = NULL,
  671. begin = 0,
  672. end = 1,
  673. inverse = FALSE
  674. ) {
  675. scale_xaringan_continuous(
  676. "color",
  677. ...,
  678. color = color,
  679. begin = begin,
  680. end = end,
  681. inverse = inverse
  682. )
  683. }
  684. #' @rdname scale_xaringan
  685. #' @export
  686. scale_xaringan_colour_continuous <- scale_xaringan_color_continuous
  687. get_theme_accent_color <- function(color = NULL, inverse = FALSE) {
  688. color <-
  689. if (!inverse) {
  690. color %||%
  691. xaringanthemer_env[["header_color"]] %||%
  692. xaringanthemer_env[["text_color"]]
  693. } else {
  694. color %||% xaringanthemer_env[["inverse_header_color"]]
  695. }
  696. if (is.null(color)) {
  697. stop(
  698. call. = FALSE,
  699. "No color provided and no default available. ",
  700. "Have you forgotten to use a style function to set the xaringan theme?"
  701. )
  702. }
  703. color
  704. }
  705. blend_colors <- function(x, y, alpha = 0.5) {
  706. x <- colorspace::hex2RGB(x)
  707. y <- colorspace::hex2RGB(y)
  708. z <- colorspace::mixcolor(alpha, x, y)
  709. colorspace::hex(z)
  710. }
  711. color_blender <- function(x, y) function(alpha = 0.5) blend_colors(x, y, alpha)
  712. hex2HCL <- function(x) {
  713. colorspace::coords(methods::as(colorspace::hex2RGB(x), "polarLUV"))
  714. }
  715. # Fonts -------------------------------------------------------------------
  716. get_theme_font <- function(element = c("text", "header", "code"), use_showtext = TRUE) {
  717. element <- match.arg(element)
  718. element_family <- paste0(element, "_font_family")
  719. element_google <- paste0(element, "_font_google")
  720. element_is_google <- paste0(element, "_font_is_google")
  721. element_url <- paste0(element, "_font_url")
  722. family <- xaringanthemer_env[[element_family]]
  723. is_google_font <- xaringanthemer_env[[element_is_google]]
  724. if (is.null(is_google_font)) {
  725. is_google_font <- !is.null(xaringanthemer_env[[element_google]]) ||
  726. grepl("fonts.google", xaringanthemer_env[[element_url]], fixed = TRUE)
  727. }
  728. register_font(
  729. family,
  730. google = is_google_font,
  731. fn = sys.calls()[[max(1, sys.nframe() - 1)]][[1]],
  732. use_showtext = use_showtext
  733. )
  734. }
  735. register_font <- function(
  736. family,
  737. google = TRUE,
  738. fn = sys.calls()[[max(1, sys.nframe() - 1)]][[1]],
  739. ...,
  740. use_showtext = TRUE
  741. ) {
  742. if (is.null(family) || !use_showtext) {
  743. return(NULL)
  744. }
  745. if (is_google_font(family)) family <- family$family
  746. family <- gsub("['\"]", "", family)
  747. if (!identical(xaringanthemer_env$showtext_auto, TRUE)) {
  748. if (!requires_package(pkg = "showtext", fn, required = FALSE)) {
  749. return(family)
  750. }
  751. showtext::showtext_auto()
  752. xaringanthemer_env$showtext_auto <- TRUE
  753. }
  754. if (family %in% xaringanthemer_env[["registered_font_families"]] %||% "") {
  755. return(family)
  756. }
  757. if (!requires_package(pkg = "sysfonts", fn, required = FALSE)) {
  758. return(family)
  759. } else if (family == "Droid Serif") {
  760. dstmp <- tempfile("droid-serif", fileext = "ttf")
  761. utils::download.file(
  762. "https://github.com/google/fonts/raw/feb15862e0c66ec0e7531ca4c3ef2607071ea700/apache/droidserif/DroidSerif-Regular.ttf",
  763. dstmp,
  764. quiet = TRUE
  765. )
  766. sysfonts::font_add(
  767. family = "Droid Serif",
  768. regular = dstmp
  769. )
  770. } else if (!family %in% sysfonts::font_families()) {
  771. is_default_font <- family %in% c(
  772. "Roboto",
  773. "Source Code Pro",
  774. "Yanone Kaffeesatz"
  775. )
  776. font_found <- family %in% sysfonts::font_families()
  777. is_google_font <- identical(google, TRUE) || (missing(google) && is_default_font)
  778. if (is_google_font) {
  779. tryCatch(
  780. {
  781. sysfonts::font_add_google(family, ...)
  782. font_found <- TRUE
  783. },
  784. error = function(e) {},
  785. warning = function(w) {}
  786. )
  787. }
  788. if (!font_found) { # warn user if font still not found
  789. msg <- if (is_google_font) glue::glue(
  790. "Font '{family}' not found in Google Fonts. ",
  791. "Please manually register the font using `sysfonts::font_add()`."
  792. ) else {
  793. glue::glue(
  794. "Font '{family}' must be manually registered using `sysfonts::font_add()`."
  795. )
  796. }
  797. warning(str_wrap(msg), call. = FALSE)
  798. } else {
  799. verify_fig_showtext(fn)
  800. }
  801. }
  802. xaringanthemer_env[["registered_font_families"]] <- c(
  803. xaringanthemer_env[["registered_font_families"]],
  804. family
  805. )
  806. family
  807. }
  808. verify_fig_showtext <- function(fn = "theme_xaringan_base") {
  809. if (is.null(knitr::current_input())) return()
  810. # Try to set fig.showtext automatically
  811. if (isTRUE(knitr::opts_current$get("fig.showtext"))) {
  812. return()
  813. }
  814. stop(str_wrap(
  815. "To use ", fn, "() with knitr, you need to set the chunk option ",
  816. "`fig.showtext = TRUE` for this chunk. Or you can set this option ",
  817. "globally with `knitr::opts_chunk$set(fig.showtext = TRUE)`."
  818. ))
  819. }
  820. requires_xaringanthemer_env <- function(
  821. css_file = NULL,
  822. try_css = TRUE,
  823. requires_theme = TRUE
  824. ) {
  825. reload <- !is.null(css_file) && isTRUE(try_css)
  826. pkg_env_exists <- exists("xaringanthemer_env")
  827. missing_theme <- requires_theme && pkg_env_exists && is.null(xaringanthemer_env$header_color)
  828. if (reload || !pkg_env_exists || missing_theme) {
  829. if (try_css) {
  830. css_vars <- read_css_vars(css_file)
  831. for (css_var in names(css_vars)) {
  832. xaringanthemer_env[[css_var]] <- css_vars[[css_var]]
  833. }
  834. return(requires_xaringanthemer_env(try_css = FALSE))
  835. } else {
  836. stop("Please call a xaringanthemer theme function first.")
  837. }
  838. }
  839. }
  840. #' Get the Value of xaringanthemer Style Setting
  841. #'
  842. #' A helper function to retrieve the value of style settings as set by a
  843. #' xaringanthemer style function, for use in plotting and other circumstances.
  844. #'
  845. #' @section Style Settings:
  846. #' Style settings used by xaringanthemer include:
  847. #'
  848. #' - `background_color`
  849. #' - `background_image`
  850. #' - `background_position`
  851. #' - `background_size`
  852. #' - `blockquote_left_border_color`
  853. #' - `code_font_family`
  854. #' - `code_font_family_fallback`
  855. #' - `code_font_google`
  856. #' - `code_font_is_google`
  857. #' - `code_font_size`
  858. #' - `code_font_url`
  859. #' - `code_highlight_color`
  860. #' - `code_inline_background_color`
  861. #' - `code_inline_color`
  862. #' - `code_inline_font_size`
  863. #' - `extra_css`
  864. #' - `extra_fonts`
  865. #' - `footnote_color`
  866. #' - `footnote_font_size`
  867. #' - `footnote_position_bottom`
  868. #' - `header_background_auto`
  869. #' - `header_background_color`
  870. #' - `header_background_content_padding_top`
  871. #' - `header_background_ignore_classes`
  872. #' - `header_background_padding`
  873. #' - `header_background_text_color`
  874. #' - `header_color`
  875. #' - `header_font_family`
  876. #' - `header_font_google`
  877. #' - `header_font_is_google`
  878. #' - `header_font_url`
  879. #' - `header_font_weight`
  880. #' - `header_h1_font_size`
  881. #' - `header_h2_font_size`
  882. #' - `header_h3_font_size`
  883. #' - `inverse_background_color`
  884. #' - `inverse_header_color`
  885. #' - `inverse_text_color`
  886. #' - `inverse_text_shadow`
  887. #' - `left_column_selected_color`
  888. #' - `left_column_subtle_color`
  889. #' - `link_color`
  890. #' - `padding`
  891. #' - `table_border_color`
  892. #' - `table_row_border_color`
  893. #' - `table_row_even_background_color`
  894. #' - `text_bold_color`
  895. #' - `text_color`
  896. #' - `text_font_base`
  897. #' - `text_font_family`
  898. #' - `text_font_family_fallback`
  899. #' - `text_font_google`
  900. #' - `text_font_is_google`
  901. #' - `text_font_size`
  902. #' - `text_font_url`
  903. #' - `text_font_weight`
  904. #' - `text_slide_number_color`
  905. #' - `text_slide_number_font_size`
  906. #' - `title_slide_background_color`
  907. #' - `title_slide_background_image`
  908. #' - `title_slide_background_position`
  909. #' - `title_slide_background_size`
  910. #' - `title_slide_text_color`
  911. #'
  912. #' @param setting A xaringanthemer style setting
  913. #' @inheritParams theme_xaringan
  914. #' @examples
  915. #' # Create a xaringanthemer style in a temporary file for this example
  916. #' xaringan_themer_css <- tempfile("xaringan-themer", fileext = ".css")
  917. #'
  918. #' style_solarized_light(outfile = xaringan_themer_css)
  919. #'
  920. #' theme_xaringan_get_value("text_color")
  921. #' theme_xaringan_get_value("background_color")
  922. #' theme_xaringan_get_value("header_color")
  923. #' theme_xaringan_get_value("text_bold_color")
  924. #'
  925. #' @export
  926. theme_xaringan_get_value <- function(setting, css_file = NULL) {
  927. requires_xaringanthemer_env(css_file = css_file)
  928. if (length(setting) > 1) {
  929. ret <- list()
  930. for (var in setting) {
  931. ret[[var]] <- xaringanthemer_env[[var]]
  932. }
  933. return(ret)
  934. }
  935. xaringanthemer_env[[setting]]
  936. }
  937. web_to_point <- function(x, px_per_em = NULL, scale = 0.75) {
  938. if (is.null(x)) {
  939. return(NULL)
  940. }
  941. px_per_em <- px_per_em %||% get_base_font_size()
  942. if (grepl("pt$", x)) {
  943. return(as.numeric(sub("pt$", "", x)))
  944. } else if (grepl("px$", x)) {
  945. x <- as.numeric(sub("px$", "", x))
  946. return(x * scale)
  947. } else if (grepl("r?em$", x)) {
  948. x <- as.numeric(sub("r?em$", "", x))
  949. return(x * px_per_em * scale)
  950. } else {
  951. return()
  952. }
  953. }
  954. get_base_font_size <- function() {
  955. base_size <- xaringanthemer_env[["base_font_size"]] %||%
  956. xaringanthemer_env[["text_font_size"]]
  957. if (!grepl("px", base_size)) {
  958. # assume 16px base font size
  959. 16
  960. } else {
  961. as.numeric(sub("px", "", base_size))
  962. }
  963. }