r - 当轴是离散的时,如何轻推 geom_text_repel 中段的起点?
问题描述
library(tidyverse)
library(ggrepel)
df <- iris %>%
pivot_longer(starts_with("Sepal")) %>%
group_by(Species, name) %>%
summarise(
y0 = min(value),
y1 = max(value)
)
我经常使用这个ggrepel
包来添加标签和注释我的 ggplots,但有时外观可能有点难以调整。作为这个问题的一个例子,我对众所周知的ìris
数据做了以下愚蠢的情节。
df %>%
ggplot(aes(x = name)) +
geom_segment(
aes(xend = name, y = y0, yend = y1, color = Species), size = 10
) +
geom_text_repel(
aes(label = Species, y = y1), direction = "y", nudge_x = .5
)
我正在寻找一种方法来调整 ggrepel 箭头的起始位置,使它们从段的右侧开始,而不是在中间。一种解决方法当然是将线段放在箭头的顶部:
df %>%
ggplot(aes(x = name)) +
geom_text_repel(
aes(label = Species, y = y1), direction = "y", nudge_x = .5
) +
geom_segment(
aes(xend = name, y = y0, yend = y1, color = Species), size = 10
)
但这只有在您没有任何透明度的情况下才有效,所以我想知道是否可能有另一种解决方案。我想我正在寻找一个nudge_x_start
或类似的东西。
编辑:@stefan 建议使用point.padding
适用于 iris 示例的参数,但不幸的是,当点彼此靠近时它不起作用。
df2 <- enframe(month.name, "y0", "label") %>%
mutate(y1 = y0 + 1)
df2 %>%
ggplot(aes(x = "month")) +
geom_segment(
aes(xend = "month", y = y0, yend = y1, color = label), size = 10
) +
geom_text_repel(
aes(label = label, y = y0 + 0.5), direction = "y", nudge_x = 1/8,
size = 5, point.padding = 1.25, hjust = 0
) +
ylim(-12*2, 12*3)
解决方案
也许这就是你要找的。即使使用离散轴ggplot2
在引擎盖下使用数字,即第一个类别位于 1,第二个位于 2,......因此,您可以x
像使用y
. 这样做您必须将映射的分类变量转换x
为数字:
library(tidyverse)
library(ggrepel)
df <- iris %>%
pivot_longer(starts_with("Sepal")) %>%
group_by(Species, name) %>%
summarise(
y0 = min(value),
y1 = max(value)
)
#> `summarise()` has grouped output by 'Species'. You can override using the `.groups` argument.
df %>%
ggplot(aes(x = name)) +
geom_segment(
aes(xend = name, y = y0, yend = y1, color = Species),
size = 10
) +
geom_text_repel(
aes(label = Species, y = y1, x = as.numeric(factor(name)) + .06),
direction = "y", nudge_x = .5
)
df2 <- enframe(month.name, "y0", "label") %>%
mutate(y1 = y0 + 1)
df2 %>%
ggplot(aes(x = "month")) +
geom_segment(
aes(xend = "month", y = y0, yend = y1, color = label), size = 10
) +
geom_text_repel(
aes(label = label, y = y0 + 0.5, x = as.numeric(factor("month")) + .025), direction = "y", nudge_x = .5,
size = 5, hjust = 0
) +
ylim(-12*2, 12*3) +
guides(color = "none")
推荐阅读
- php - 如果未选中,则将复选框值设为零
- php - PHP - 如何在 WP 上随机显示一个类别的帖子
- azure - 如何限制每个节点附加托管磁盘的 pod 数量
- angular - 在 index.html 中使用 Angular 6 中的字体真棒图标
- c# - 如何在播放视频时停止 C# VLC 播放器打开 Direct3D 输出窗口?
- html - 使用 td 类隐藏表格中的一行
- c# - C# Entity Framework 迁移,使 ID 自动递增
- php - 创建交互式数据表以从 MySQLi 数据库中提取数据
- android - 如何在android studio中获取设备的屏幕唤醒时间?
- java - Java - 将空引用传递给构造函数的对象并稍后创建实例