有什么方法可以在 ggplot 中的 y 轴标签旁边添加自定义符号?我想在每个赛车手的名字旁边添加一个小圆圈,表明他们各自的线条颜色如下图(也可以识别出玛丽亚的蓝色更紫色,但那是为您准备的 MS Paint)。
library(ggplot2)
library(scales)
dat <- data.frame(name = c(rep("bill", 3), rep("maria", 3), rep("claudio", 3)),
lap = rep(0:2, 3),
pos = c(1, 1, 2,
2, 3, 1,
3, 2, 3))
dat %>%
ggplot(aes(x = lap, y = pos, color = name)) +
geom_line() +
scale_y_reverse(breaks = 1:3,
labels = function(x) {
dat$name[dat$lap == 0][order(dat$pos[dat$lap == 0])][x]
},
sec.axis = sec_axis(function(x) x,
breaks = 1:3, labels = label_ordinal())) +
scale_x_continuous(breaks = pretty_breaks(3)) +
theme(legend.position = "none")
答案 0 :(得分:2)
这不是您问题的答案,而是解决类似问题的替代方法。您可以使用 ggtext()
包将文本本身着色为与您的线条相同的颜色,而不是试图摆弄符号。
你需要三样东西:
labels
参数library(ggplot2)
library(scales)
library(ggtext)
#> Warning: package 'ggtext' was built under R version 4.0.3
dat <- data.frame(name = c(rep("bill", 3), rep("maria", 3), rep("claudio", 3)),
lap = rep(0:2, 3),
pos = c(1, 1, 2,
2, 3, 1,
3, 2, 3))
colors <- hue_pal()(3)[c(1,3,2)]
labels <- glue::glue("<i style='color:{colors}'>{unique(dat$name)}</i>")
ggplot(dat, aes(x = lap, y = pos, color = name)) +
geom_line() +
scale_y_reverse(breaks = 1:3,
labels = labels,
sec.axis = sec_axis(function(x) x,
breaks = 1:3, labels = label_ordinal())) +
scale_x_continuous(breaks = pretty_breaks(3)) +
theme(legend.position = "none",
axis.text.y.left = element_markdown())
由 reprex package (v0.3.0) 于 2021 年 1 月 3 日创建
编辑:如果您坚持使用圆圈,您可以采用相同的方法为 unicode 圆圈字符着色。使用下面的代码代替之前的 labels
。
labels <- glue::glue("{unique(dat$name)} <i style='color:{colors}'>\u25CF</i>")