gpt4 book ai didi

r - 将标签从 geom_label_repel 移动到 ggplot 边缘

转载 作者:行者123 更新时间:2023-12-04 02:55:26 25 4
gpt4 key购买 nike

在下面的图中,我想将标签“V-Engine”移到绘图边距中。调整 nudge_x 参数是移动“S-Engine”标签而不是“V-Engine”标签。

library(ggplot2)
library(ggrepel)
library(dplyr)

ds <-
mtcars %>%
mutate(vs = factor(vs, labels = c("V-Engine", "S-Engine"))) %>%
# Create labels for the rightmost data points
group_by(vs) %>%
mutate(
label =
case_when(
wt == max(wt) ~ as.character(vs),
TRUE ~ NA_character_
)
) %>%
ungroup()

ds %>%
ggplot(aes(x = wt, y = mpg, color = vs)) +
geom_smooth(se=FALSE) +
geom_label_repel(aes(label = label), nudge_x = 1, na.rm = TRUE) +
guides(color = FALSE) +
theme_minimal() +
theme(plot.margin = unit(c(1,3,1,1), "cm"))

enter image description here

最佳答案

您可以在 geom_label_repel 中设置 xlim()

library(dplyr)
library(ggplot2)
library(ggrepel)

ds %>%
ggplot(aes(x = wt, y = mpg, color = vs)) +
geom_smooth(se=FALSE) +
geom_label_repel(aes(label = label),
nudge_x = 1,
# direction = 'x',
xlim = c(0, 6.5),
na.rm = TRUE) +
guides(color = FALSE) +
theme_minimal() +
theme(plot.margin = unit(c(1,3,1,1), "cm")) +
coord_cartesian(clip = 'off')
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

reprex package 创建于 2018-11-16 (v0.2.1.9000)

关于r - 将标签从 geom_label_repel 移动到 ggplot 边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53346606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com