[英]Annotate a geom_smooth line in ggplot
給定以下虛擬數據集
df = structure(list(date = structure(c(19128, 19129, 19130, 19131,
19132, 19133, 19134, 19135, 19136, 19137, 19138, 19139, 19140,
19141, 19142, 19143, 19144), class = "Date"), av7 = c(108.55,
108.875, 108.916666666667, 108.725, 108.92, 108.877777777778,
108.841666666667, 108.70119047619, 108.525, 108.329761904762,
108.115476190476, 107.94880952381, 107.877380952381, 107.652380952381,
107.609523809524, 107.495238095238, 107.390476190476), ch7 = c(-0.15,
-0.35, -0.59, -0.61, -0.97, -1, 0, 0.15, -0.35, -0.59, -0.61, -0.97, -1,
-1.19, -1.09, -1.03, -0.94)), row.names = c(NA, -17L), class = c("tbl_df",
"tbl", "data.frame"))
我想為av7
變量繪制一條平滑的線,並用ch7
變量的值對該線進行注釋。 我試過這段代碼:
ggplot(df, aes(x = date, y=av7, label = ch7))+
geom_smooth(se=F)+
geom_text(nudge_y = 0.2)
但是,正如您在下面看到的,label 的 position 不與平滑線對齊,因為它遵循原始點的 position:
我還嘗試使用stat = "smooth"
witin geom_text
如下:
ggplot(df, aes(x = date, y=av7, label = ch7))+
geom_smooth(se=F)+
geom_text(nudge_y = 0.2,
stat = "smooth")
但我收到以下錯誤:
Error: geom_text requires the following missing aesthetics: label
任何幫助將非常感激。
如果 x 定位不是很重要,那么您也可以使用 geomtextpath package。遺憾的是,它目前每行只允許一個 label ,因此您只能折疊標簽並偽造它在整行上的分布。 只有當你想或多或少地平均分布在曲線上時,這才有效。
library(geomtextpath)
#> Loading required package: ggplot2
df = structure(list(date = structure(c(19128, 19129, 19130, 19131,
19132, 19133, 19134, 19135, 19136, 19137, 19138, 19139, 19140,
19141, 19142, 19143, 19144), class = "Date"), av7 = c(108.55,
108.875, 108.916666666667, 108.725, 108.92, 108.877777777778,
108.841666666667, 108.70119047619, 108.525, 108.329761904762,
108.115476190476, 107.94880952381, 107.877380952381, 107.652380952381,
107.609523809524, 107.495238095238, 107.390476190476), ch7 = c(-0.15,
-0.35, -0.59, -0.61, -0.97, -1, 0, 0.15, -0.35, -0.59, -0.61, -0.97, -1,
-1.19, -1.09, -1.03, -0.94)), row.names = c(NA, -17L), class = c("tbl_df",
"tbl", "data.frame"))
ggplot(df, aes(x = date, y = av7)) +
geom_textsmooth(aes(label = paste(ch7, collapse = " ")))
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
由reprex package (v2.0.1) 創建於 2022-06-01
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.