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

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