在 y 轴标签旁边添加自定义符号

时间:2021-01-03 05:40:25

标签: r ggplot2

有什么方法可以在 ggplot 中的 y 轴标签旁边添加自定义符号?我想在每个赛车手的名字旁边添加一个小圆圈,表明他们各自的线条颜色如下图(也可以识别出玛丽亚的蓝色更紫色,但那是为您准备的 MS Paint)。

enter image description here

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")

1 个答案:

答案 0 :(得分:2)

这不是您问题的答案,而是解决类似问题的替代方法。您可以使用 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 (v0.3.0) 于 2021 年 1 月 3 日创建

编辑:如果您坚持使用圆圈,您可以采用相同的方法为 unicode 圆圈字符着色。使用下面的代码代替之前的 labels

labels <- glue::glue("{unique(dat$name)} <i style='color:{colors}'>\u25CF</i>")