Home > Net >  Add geom_point for specific geom_area in ggplot2
Add geom_point for specific geom_area in ggplot2

Time:11-16

With sample and code below, I'm trying to reproduce the effect of an image by adding geom_point for only type 3 data as shown in the end of this question:

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()

Out:

enter image description here

As I add geom_point(size=2) to the code, it add points for all data points, how could I add geom_point only for data's type is 3? Sincere thanks.

enter image description here

CodePudding user response:

You can use the data argument of geom_point to restrict the points being plotted. So replace your geom_point(size=2) call with geom_point(data=df[type==3], size=2)

(note this syntax only works because per the question df is a data.table, use df[df$type==3,] otherwise)

enter image description here

An alternative, if you didn't want the legend to include the points for the other two types would be to set the shape to NA for the types you didn't want to include:

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

enter image description here

CodePudding user response:

Not sure if I understood your question but try :

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()

Out:

enter image description here

  • Related