ggrepel与geom_smooth一起

发布于 2025-02-13 01:45:20 字数 631 浏览 2 评论 0原文

ggplot(gapminder::gapminder,aes(x=year,y=lifeExp,label=continent,color=continent))+
geom_line(size=.1,alpha=.2)+
guides(color="none")+
theme_minimal()+
geom_smooth(aes(color=continent),se=F,method="loess")+
ggrepel::geom_label_repel(direction = "y",stat="smooth",nudge_x = 5)

导致以下结果:

我只想为每个大陆的每个平滑骨料提供一个标签。

我尝试调整参数,但没有帮助。如果我跳过stat =“ smooth”GEOM_LABEL_REPEL中的术语,它将变成所有干草,并试图标记所有单个行 - 而不是平滑的线条。有什么想法吗?

ggplot(gapminder::gapminder,aes(x=year,y=lifeExp,label=continent,color=continent))+
geom_line(size=.1,alpha=.2)+
guides(color="none")+
theme_minimal()+
geom_smooth(aes(color=continent),se=F,method="loess")+
ggrepel::geom_label_repel(direction = "y",stat="smooth",nudge_x = 5)

Results in the following:
enter image description here

I only want one label for each smoothed aggregate for each continent.

I´ve tried tweaking the parameters, but to no help. If I skip the stat="smooth" term from geom_label_repel It goes all haywire and tries to label all the individual lines - not the smoothed lines. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

全部不再 2025-02-20 01:45:23

您可以做到这一点的一种方法是在摘要标签数据框中获取每个大陆的最后一个(或第一个等)拟合的值,然后在ggrepel中使用该值:

library(tidyverse)
library(gapminder)
library(ggrepel)
library(broom)

label_df <- gapminder |> 
  nest(data = -continent) |> 
  mutate(model = map(data, ~loess(lifeExp ~ year, .x)),
         augmented = map(model, augment),
         fitted = map(augmented, ".fitted") |> map_dbl(last),
         year = map(data, "year") |> map_int(last)) |> 
  select(continent, fitted, year)

ggplot(gapminder, aes(year, lifeExp, color = continent)) +
  geom_line(size = .1, alpha = .2) +
  guides(color = "none") +
  theme_minimal() +
  geom_smooth(aes(color = continent), se = F, method = "loess") +
  geom_label_repel(aes(year, fitted, label = continent), data = label_df)

”“

在2022-07-03创建的 reprex软件包(v2.0.1)

One way you could do this is to get the last (or first etc. as desired) fitted value for each continent in a summary label data frame, then use that in ggrepel:

library(tidyverse)
library(gapminder)
library(ggrepel)
library(broom)

label_df <- gapminder |> 
  nest(data = -continent) |> 
  mutate(model = map(data, ~loess(lifeExp ~ year, .x)),
         augmented = map(model, augment),
         fitted = map(augmented, ".fitted") |> map_dbl(last),
         year = map(data, "year") |> map_int(last)) |> 
  select(continent, fitted, year)

ggplot(gapminder, aes(year, lifeExp, color = continent)) +
  geom_line(size = .1, alpha = .2) +
  guides(color = "none") +
  theme_minimal() +
  geom_smooth(aes(color = continent), se = F, method = "loess") +
  geom_label_repel(aes(year, fitted, label = continent), data = label_df)

Created on 2022-07-03 by the reprex package (v2.0.1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文