【发布时间】:2021-05-17 21:54:33
【问题描述】:
我使用 ggtext 包来格式化由 ggplot2 制作的绘图的轴标签,特别是函数 element_textbox_simple(),我在 html 格式中存在一些问题,以在单词之间引入空格或空格。
在上图中,每个轴标签都有两个级别:
- 变量名称(例如 niceness)
- 带有标签的第二行描述了相应轴的每个极值(例如 jerk - nice)
为了实现这个“多级标签”,我使用 ggtext 来格式化带有以下 html 表达式的标签:
<br><span style = 'font-size:8pt'>Niceness</br><br><span style='word-spacing:20pt;font-size:10pt;color:red'>JERK NICE</span></br>"
我的问题是属性word-spacing 不起作用,我需要将每个轴的“带有标签的第二行”间隔到轴的极端。例如,在情节中,我想用许多空格替换 JERK 和 NICE 之间的文本。我尝试使用nbsp;,它假设编码一个空格但没有成功,它只将两个标签分隔一个默认空间。有什么想法吗?
您可以通过以下方式重现情节:
library(ggplot2)
library(ggtext)
library(latex2exp)
# Multivariate normal dist parameters:
mu <- c(50, 50)
Sigma <- matrix(c(200, 4, 8, 200), 2)
# Generate 10.000 data points
set.seed(323)
df <- as.data.frame(MASS::mvrnorm(5e3, mu, Sigma))
# Compute correlation between V1 and V2
cor0 <- round(cor(df$V1, df$V2), 2)
# Initial plot
p0 <- df %>%
ggplot() +
geom_point(aes(V1, V2), alpha = .3, size = .2) +
scale_x_continuous(breaks = seq(0, 100, 20), n.breaks = seq(0, 100, 5)) +
scale_y_continuous(breaks = seq(0, 100, 20)) +
coord_cartesian(xlim = c(0, 100), ylim = c(0, 100)) +
labs(x = "<br><span style = 'font-size:8pt'>Niceness</br><br><span style='word-spacing:5pt;font-size:10pt;color:red'>JERK (replace this text by a blank separation between these two extrem label descriptions) NICE</span></br>",
y = "<br><span style = 'font-size:8pt'>Attractiveness</br><br><span style = 'font-size:10pt;color:red'>NOT (replace this text by a blank separation between these two extrem label descriptions) HOT</span></br>",
title = TeX(paste("$\\rho$ =", as.character(cor0)))) +
theme_bw(base_size = 8) +
theme(plot.title = element_text(hjust = 0.5),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.title.x = element_textbox_simple(
margin = margin(0, 100, 15, 100),
halign = 0.5
),
axis.title.y = element_textbox_simple(
margin = margin(0, 0, 0, 0),
orientation = "left-rotated",
halign = 0.5
))
【问题讨论】:
-
package documentation 中的注释:“提供渲染支持的 gridtext 包仅实现了极其有限的 Markdown/HTML/CSS 子集”。看起来不支持“字间距”。如果你愿意,你可以提交一个 github 问题。
-
我可以看到你努力制作一个可重复的例子 - 但你错过了对 magrittr 的调用(对于管道)(或只是 tidyverse),或者不清楚
TeX()来自哪里 -
为了避免这种情况 - 我建议使用
reprex包 -
@tjebo 你是对的,缺少的依赖是
latex2exp::TeX();迟到了,我会按照你的建议修改问题以使用reprex