簡體   English   中英

為 ggplot2 中的特定 geom_area 添加 geom_point

[英]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? 真誠的感謝。

在此處輸入圖片說明

您可以使用geom_pointdata參數來限制正在繪制的點。 所以用geom_point(data=df[type==3], size=2)替換你的geom_point(size=2)調用

(請注意,此語法僅有效,因為根據問題dfdata.table ,否則使用df[df$type==3,]

在此處輸入圖片說明

另一種方法是,如果您不希望圖例包含其他兩種類型的點,則可以將不想包含的類型的形狀設置為NA

 geom_point(size=2, aes(shape=type)) +
  scale_shape_manual(values=c("1"=NA, "2"=NA, "3"=19))+

在此處輸入圖片說明

不確定我是否理解您的問題,但請嘗試:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM