我试图让标签与一条平滑线上的值对齐。虽然我看到的其他答案建议创建预测值的数据列,但我正在寻找一种更干净的替代方案,它使用已经为ggplot生成的数据。
有关问题,请参见下面的示例:
require(tidyverse)
require(ggrepel)
set.seed(1)
df <- data.frame(x = rep(1:100, 5), y = c(sample(1:20, 100, T), sample(21:40, 100, T), sample(41:60, 100, T), sample(61:80, 100, T), sample(81:100, 100, T)), group = rep(letters[1:5], each = 100))
df <- tbl_df(df)
df %>%
ggplot(aes(x = x, y = y, label = group, color = group)) +
geom_smooth() +
guides(color = F) +
geom_text_repel(data = . %>% filter(x == max(x)), aes(x = x, y = y, label = group), nudge_x = 50)

是否有某种方法可以在不使用ggplot_build()或其他外部多步方法的情况下获得max(x)处的平滑线值?
发布于 2017-08-08 08:24:32
我不确定这是否真的更优雅,但这一切都在一个管道中。我手头没有“排斥”版本,但想法是一样的。
library(broom)
df %>%
{ggplot(., aes(x, y, label = group, color = group)) +
geom_smooth() +
guides(color = F) +
geom_text(data = group_by(., group) %>%
do(augment(loess(y~x, .))) %>%
filter(x == max(x)),
aes(x, .fitted), nudge_x = 5)}

你需要得到最终x值下的黄土平滑度的预测值,所以你只需要对它进行两次拟合。如果模型拟合很慢,您可以在dplyr链中更高的位置执行一次,然后在图的其余部分使用输出。
df %>%
group_by(group) %>%
do(augment(loess(y~x, .))) %>%
{ggplot(., aes(x, y, label = group, color = group)) +
geom_smooth() +
guides(color = F) +
geom_text(data = filter(., x == max(x)),
aes(x, .fitted), nudge_x = 5)}https://stackoverflow.com/questions/45556998
复制相似问题