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

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

最佳答案

这不是您问题的答案,而是解决类似问题的替代方案。您可以使用 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/

相关文章:

r - 将分面标题注释为分面上的 strip

r - 如何使用 ggarrange() 或类似方法手动调整合并图的高度

r - 组合来自两个不同数据集的图表

r - 将动态值添加到 RMySQL getQuery 中

r - 循环遍历数据框的列以使用 ggplot2 创建图

r - 为什么不能计算表达式中的这个 R 调用对象? (子集与从调用对象中提取)

python 情节9: how to change color scale

r - 如何将ggplot图标题居中

r - 将 gganimate 与 geom_point 和 geom_line 结合使用

r - 如何读取列名为 "Hebrew"的表(在 R 中)?