😎 Give your xaringan slides some style
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1011 Zeilen
31KB

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