有没有办法在 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")
最佳答案
这不是您问题的答案,而是解决类似问题的替代方案。您可以使用 ggtext() 包将文本本身着色为与线条相同的颜色,而不是尝试摆弄符号。
你需要三样东西:
- 用 html 语法为文本着色
- 提供彩色文本作为
labels
参数 - 设置主题元素以将文本解释为 markdown
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 于 2021 年 1 月 3 日创建(v0.3.0)
编辑:如果您坚持使用圆形,则可以采用相同的方法为 unicode 圆形字符着色。使用下面的代码代替之前的标签
。
labels <- glue::glue("{unique(dat$name)} <i style='color:{colors}'>\u25CF</i>")
关于r - 在 y 轴标签旁边添加自定义符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65546968/