使用下面的示例和代碼,我試圖通過僅為型別 3 資料添加 geom_point 來重現影像的效果,如本問題末尾所示:
library(data.table)
library(ggplot2)
df <- structure(list(date = c("2021-07-31", "2021-08-31", "2021-09-07",
"2021-09-14", "2021-09-21", "2021-09-30", "2021-10-7", "2021-10-14",
"2021-10-21", "2021-10-31", "2021-11-30", "2021-12-31", "2022-1-31",
"2022-2-28"), value = c(190.3, 174.9, 163.2, 168.4, 168.6, 168.2,
163.5, 161.6, 172.9, 166.5, 175.2, 197.7, 212.1, 177.9), type = c(1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L)), class = "data.frame", row.names = c(NA,
-14L))
df$type <- as.factor(df$type)
df$date <- as.Date(df$date)
setDT(df, key = "date")
types.extend <- c(1)
new.values <- df[, .SD[1], by = .(type)][, type := shift(type, type = "lag")][type %in% types.extend,]
# bind the new value to your original data
df <- rbind(df, new.values)
ggplot(data = df,
aes(x=date, y=value, group=type, color = type, fill = type))
geom_area(alpha=0.4, position = "identity")
geom_point(size=2)
scale_color_manual(values=c("1" = "gray", "2" = "red", "3" = "blue"),
aesthetics = c("color", "fill"), name = "type")
theme_bw()
出去:

當我添加geom_point(size=2)到代碼時,它為所有資料點添加了點,我怎么能只為資料型別為 3 添加 geom_point?真誠的感謝。

uj5u.com熱心網友回復:
您可以使用data引數 ofgeom_point來限制正在繪制的點。所以替換你的geom_point(size=2)電話geom_point(data=df[type==3], size=2)
(請注意,此語法僅適用,因為每個問題df是 a data.table,df[df$type==3,]否則使用)

另一種選擇,如果您不希望圖例包含其他兩種型別的點,則將形狀設定NA為您不想包含的型別:
geom_point(size=2, aes(shape=type))
scale_shape_manual(values=c("1"=NA, "2"=NA, "3"=19))

uj5u.com熱心網友回復:
不確定我是否理解您的問題,但請嘗試:
ggplot(data = df,
aes(x=date, y=value, group=type, color = type, fill = type))
geom_area(alpha=0.4, position = "identity")
geom_point(data = filter(df, type == 3), aes(x=date, y=value, group=type), size = 2)
scale_color_manual(values=c("1" = "gray", "2" = "red", "3" = "blue"),
aesthetics = c("color", "fill"), name = "type")
theme_bw()
出去:

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/358867.html
