我看到很多将下标和上标放入绘图标签的示例,但我很好奇如何将下标添加到最终可用于绘图的字符向量。
示例数据和绘图:
data.frame(site = LETTERS[1:10],
a1 = c(rep(1, 7), rep(NA, 3)),
a2 = c(rep(NA, 4), rep(2, 6)),
minY = sample(1:9, 10, replace = TRUE),
maxY = sample(10:19, 10, replace = TRUE)) %>%
mutate(label = case_when(is.na(a1) ~ paste(site, a2, sep = ""),
is.na(a2) ~ paste(site, a1, sep = ""),
TRUE ~ paste(site, paste(a1, a2, sep = ","), sep = ""))) %>%
ggplot() +
geom_segment(aes(x = label, xend = label, y = minY, yend = maxY))
如何让1和2成为剧情的下标?
以编程方式形成表达式/引用字符串(例如,
A[2]
),然后使用scales::label_parse()
.
plotmath
(这是内部完成的方式),我们需要明确逗号分隔的下标。虽然单个数字具有 A[1]
的“表达式”(符号),但我们不能使用 A[1,2]
,因为 ,2
将从视图中删除;相反,我们需要 A[1*','*2]
,它是数字 1 后跟(在数学语法中相乘)字符串文字逗号后跟数字 2。
data.frame(site = LETTERS[1:10],
a1 = c(rep(1, 7), rep(NA, 3)),
a2 = c(rep(NA, 4), rep(2, 6)),
minY = sample(1:9, 10, replace = TRUE),
maxY = sample(10:19, 10, replace = TRUE)) %>%
mutate(
label = sprintf("%s[%s]", site, # CHANGED
mapply(function(x, y) paste(na.omit(c(x, y)), collapse = "*','*"), a1, a2))
) %>%
ggplot() +
geom_segment(aes(x = label, xend = label, y = minY, yend = maxY)) +
scale_x_discrete(labels = scales::label_parse()) # NEW
注意:这几乎是几个问题的重复,例如How to use subscripts in ggplot2 legends [R],尽管我找不到合适的措辞来解决这个问题。