😎 Give your xaringan slides some style
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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