r - 在 y 轴标签旁边添加自定义符号
问题描述
有什么方法可以在 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
参数 - 设置主题元素以将文本解释为降价
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 包(v0.3.0)于 2021-01-03 创建
编辑:如果您坚持使用圆圈,您可以采用相同的方法为 unicode 圆圈字符着色。使用下面的代码而不是前面的labels
.
labels <- glue::glue("{unique(dat$name)} <i style='color:{colors}'>\u25CF</i>")
推荐阅读
- javascript - 如何使网站垂直缓慢滚动,同时仍保持对滚动的控制
- python - 当数据库已经有表时,有没有更好的方法来创建模型
- google-apps-script - 在 Google 表格中,如何编写脚本将每张图纸移动到工作表上的特定位置?
- php - 如何将图标从 SVG 更改为 IMG?
- c# - HttpClient 是我在 .NET Core MVC 中使用 API 的最佳选择吗
- c++ - 基于 *inner* 类型的智能指针专门化模板
- ubuntu - 不同Linux发行版的ansible相同剧本
- c++ - 如何更改 PCD 中点的颜色?
- php - 修改 Wordpress 以允许自定义 PHP
- python - python 抓取新闻文章中的 HTTPError 错误