我有一个示例 data.table 如下
dt <- structure(list(x = c(-5.08454829941579, -5.03954101414227, -4.96110744424707,
-3.91467506637747, -3.08288789758443, -2.10944056281588, -1.35385839597117,
-0.991302108693737, -0.747580793596581, 0.021222777307317, 1.04703618291297,
1.71724303836327, 1, 0), y = c(38.7610606189486, 39.1292360562013,
25.6794493857896, 29.2344899886708, 30.0047839165718, 34.1031239345073,
40.5743610428116, 43.4840735782065, 34.863487579448, 33.6026425302808,
41.2960346180424, 42.0262260478778, 47.1194103133183, 59.6173834356779
), seq = 1:14), row.names = c(NA, -14L), class = c("data.table",
"data.frame"))
> dt
x y seq
1: -5.08454830 38.76106 1
2: -5.03954101 39.12924 2
3: -4.96110744 25.67945 3
4: -3.91467507 29.23449 4
5: -3.08288790 30.00478 5
6: -2.10944056 34.10312 6
7: -1.35385840 40.57436 7
8: -0.99130211 43.48407 8
9: -0.74758079 34.86349 9
10: 0.02122278 33.60264 10
11: 1.04703618 41.29603 11
12: 1.71724304 42.02623 12
13: 1.00000000 47.11941 13
14: 0.00000000 59.61738 14
我使用以下代码创建了一个图表 -
library(ggplot2)
library(data.table)
dt %>% ggplot(aes(x, y)) +
geom_point() + geom_path(alpha = 0.25) +
stat_smooth(method = lm, formula = y ~ poly(x, 5), se = FALSE)
有没有办法确保平滑的线按照seq
列中的顺序?我有一些点应该构成一个完整的圆圈的情况。
另外,如何增加平滑线的平滑度,使其更接近图上的点?
谢谢!
答案 0 :(得分:1)
看起来您不想要stat/geom_smooth()
,因为我认为您不想回归y ~ x
(这是统计数据所做的),您只想要一条平滑的线。我想建议改用 ggforce::geom_bspline()
。下面的例子:
library(ggplot2)
library(ggforce)
dt <- structure(list(
x = c(-5.08454829941579, -5.03954101414227, -4.96110744424707,
-3.91467506637747, -3.08288789758443, -2.10944056281588, -1.35385839597117,
-0.991302108693737, -0.747580793596581, 0.021222777307317, 1.04703618291297,
1.71724303836327, 1, 0),
y = c(38.7610606189486, 39.1292360562013,
25.6794493857896, 29.2344899886708, 30.0047839165718, 34.1031239345073,
40.5743610428116, 43.4840735782065, 34.863487579448, 33.6026425302808,
41.2960346180424, 42.0262260478778, 47.1194103133183, 59.6173834356779
), seq = 1:14),
row.names = c(NA, -14L), class = c("data.table", "data.frame"))
ggplot(dt, aes(x, y)) +
geom_point() +
geom_bspline()
由 reprex package (v0.3.0) 于 2021 年 3 月 12 日创建