这是最终 ggtext 包应该能够以一般方式完成的事情,但到目前为止,它的 HTML 呈现代码太有限了。一个新的渲染引擎正在开发中,它支持更多的 CSS,包括 CSS 选择器,这使得以通用方式将格式设置为特定数据值成为可能。它还支持text-align
左对齐文本所需的属性。
下面是如何工作的两个示例。一旦新的渲染引擎集成到 ggtext 中,您将不再需要帮助代码。
# packages needed
library(ggplot2)
library(dplyr)
library(glue)
library(rlang)
library(sinab) # remotes::install_github("clauswilke/sinab")
# helper code that will eventually live in the ggtext package
element_html <- function(css = NULL, family = NULL, face = NULL, size = NULL, colour = NULL, fill = NULL,
linetype = NULL, linewidth = NULL, hjust = NULL, vjust = NULL, lineheight = NULL,
margin = NULL, width = NULL, height = NULL, color = NULL,
debug = FALSE, inherit.blank = FALSE) {
if (!is.null(color))
colour <- color
# doesn't work with other values at this time
hjust <- 0
vjust <- 1
structure(
list(
css = css,
family = family, face = face, size = size, colour = colour, fill = fill,
linetype = linetype, linewidth = linewidth, hjust = hjust, vjust = vjust,
lineheight = lineheight, margin = margin, width = width, height = height,
debug = debug, inherit.blank = inherit.blank),
class = c("element_html", "element_text", "element")
)
}
element_grob.element_html <- function(element, label = "", x = NULL, y = NULL,
family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, lineheight = NULL,
margin = NULL, ...) {
if (is.null(label))
return(ggplot2::zeroGrob())
# for now we ignore hjust and vjust, it doesn't work yet
hj <- 0
vj <- 1
css <- element$css %||% ""
html_grob(
label, x = x, y = y, hjust = hj, vjust = vj,
width = element$width, height = element$height,
css = css
)
}
# CSS styling
css <- '
p { text-align: center; padding-top: 2px; }
.setosa { text-align: left; }
'
# plotting code
iris %>%
mutate(
# set class attribute to species name
facet_label = glue('<p class = "{Species}">{Species}</p>')
) %>%
ggplot(aes(x = Petal.Width, y = Sepal.Length)) +
facet_grid(. ~ facet_label) +
geom_point() +
theme(strip.text = element_html(css = css))
![](https://i.imgur.com/0stvJTg.png)
# another example with different styling
css <- '
p { text-align: center; padding-top: 2px; font-style: italic; }
.setosa { background-color: #0072B2; color: white; }
.versicolor { background-color: #E69F00; }
.virginica { background-color: #009E73; color: white; }
'
# plotting code
iris %>%
mutate(
# set class attribute to species name
facet_label = glue('<p class = "{Species}">I. {Species}</p>')
) %>%
ggplot(aes(x = Petal.Width, y = Sepal.Length, color = Species)) +
facet_grid(. ~ facet_label) +
geom_point() +
scale_color_manual(
values = c(
setosa = "#0072B2", versicolor = "#E69F00", virginica = "#009E73"
),
guide = "none"
) +
theme_bw() +
theme(
strip.background = element_blank(),
strip.text = element_html(css = css)
)
![](https://i.imgur.com/5dWS3rb.png)
由reprex 包(v0.3.0)于 2020 年 9 月 16 日创建