[英]Add geom_point for specific geom_area in ggplot2
使用下面的示例和代碼,我試圖通過僅為類型 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? 真誠的感謝。
不確定我是否理解您的問題,但請嘗試:
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()
出去:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.