问题描述
我认识到此问题与,但是那里的解决方案不再起作用(使用method="last.qp"
),所以我再次询问.
I recognize that this question is a close duplicate of this one, but the solution there no longer works (using method="last.qp"
), so I'm asking it again.
基本问题是,我想使用directlabels
(或等价物)来标记每个组(来自stat_smooth()
)的平滑均值,而不是实际数据.下面的示例显示的距离与我接近,但标签无法识别分组,甚至无法识别平滑线.相反,我在最后一点得到了标签.我想要的是在每条平滑线的末尾使用颜色协调的文本,而不是图右侧的图例.
The basic issue is that I'd like to use directlabels
(or equivalent) to label smoothed means for each group (from stat_smooth()
), rather than the actual data. The example below shows as close as I've gotten, but the labels aren't recognizing the grouping, or even the smoothed line. Instead, I'm getting the label at the last point. What I'd like is colour-coordinated text at the end of each smoothed line, rather than the legend on the right of the plot.
这是一个例子:
library(ggplot2)
library(directlabels)
## Data
set.seed(10)
d <- data.frame(x=seq(1,100,1), y=rnorm(100, 3, 0.5))
d$z <- ifelse(d$y>3,1,0)
## Plot
p <- ggplot(d, aes(x=x, y=y, colour=as.factor(z))) +
stat_smooth(inherit.aes=T, se=F, span=0.8, show.legend = T) +
geom_line(colour="grey50") +
scale_x_continuous(limits=c(0,110)) +
geom_dl(label="text", method="maxvar.points", inherit.aes=T)
p
这使该情节:
推荐答案
A solution using ggrepel
package based on this answer
library(tidyverse)
library(ggrepel)
set.seed(123456789)
d <- data.frame(x = seq(1, 100, 1), y = rnorm(100, 3, 0.5))
d$z <- ifelse(d$y > 3, 1, 0)
labelInfo <-
split(d, d$z) %>%
lapply(function(t) {
data.frame(
predAtMax = loess(y ~ x, span = 0.8, data = t) %>%
predict(newdata = data.frame(x = max(t$x)))
, max = max(t$x)
)}) %>%
bind_rows
labelInfo$label = levels(factor(d$z))
labelInfo
#> predAtMax max label
#> 1 2.538433 99 0
#> 2 3.293859 100 1
ggplot(d, aes(x = x, y = y, color = factor(z))) +
geom_point(shape = 1) +
geom_line(colour = "grey50") +
stat_smooth(inherit.aes = TRUE, se = FALSE, span = 0.8, show.legend = TRUE) +
geom_label_repel(data = labelInfo,
aes(x = max, y = predAtMax,
label = label,
color = label),
nudge_x = 5) +
theme_classic()
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
由 reprex程序包(v0.2.0)创建于2018-06-11.
Created on 2018-06-11 by the reprex package (v0.2.0).
这篇关于将直接标签添加到geom_smooth而不是geom_line的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!