Home > Software engineering >  how to define line color and show two legend block in one plot
how to define line color and show two legend block in one plot

Time:10-06

I have a df like below and I would like to generate a plot :

df<-structure(list(AVAL = c(36.9, 37.2, 36.5, 36.7222222222222, 36.9, 
36.9, 36.9, 37.2, 36.9), ADY = c(-9, -1, 1, 8, 15, 15, 15, 22, 
35), PARAMCD = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
), .Label = "VSTEMP", class = "factor"), Flag = c(NA, NA, NA, 
8, 15, 15, 15, 22, NA), AESER = c(NA, NA, NA, "N", "N", "N", 
"N", "Y", NA)), row.names = 546:554, class = "data.frame")

ggplot(data =df) 
    geom_line(data=df[!is.na(df$AVAL),],aes(x = ADY, y = AVAL, color = PARAMCD, yaxs="d", xaxs="d"),size=0.8) 
    geom_point(data=df[!is.na(df$AVAL),], aes(x = ADY, y = AVAL)) 
    geom_vline(aes(xintercept=Flag, color=AESER),lty='dashed')

My plot is look like following:

enter image description here

I wonder whether it is possible to define the vertical line as black for AESER=="N", and red for AESER=="Y"? Also for the legend, is it possible to just show the one for vertical lines? or is it a better way to present the legend, maybe one block for measure item VSTERM, and then another one for AESER: Y|N? Could anyone guide me on this? Thanks.

CodePudding user response:

Option 1:

In case a single legend for the vertical line and the geom_line Y/N/VSTEMP is enough, this should do it:

ggplot(data =df[!is.na(df$AVAL),], aes(x = ADY, y = AVAL)) 
    geom_line(aes(color = 'PARAMCD')), size=0.8)   
    geom_point()  
    geom_vline(aes(xintercept=Flag, color=AESER), lty='dashed')  
    scale_color_manual(name = "legend_name", values = c(N = "black", Y = "red", VSTEMP = "green")) 

Option 2:

In the case of a single legend for the vertical line Y/N:

ggplot(data =df[!is.na(df$AVAL),], aes(x = ADY, y = AVAL)) 
  geom_line(color='green', size=0.8) 
  geom_point() 
  geom_vline(aes(xintercept=Flag, color=AESER), lty='dashed')  
  scale_color_manual(name = "legend_name", values = c(N = "black", Y = "red")) 

output:

plot

CodePudding user response:

Here is a way. Add a scale_color_manual with the colors you want in the plot.

library(ggplot2)

ggplot(data = df[!is.na(df$AVAL), ], aes(x = ADY, y = AVAL))  
  geom_line(aes(color = PARAMCD), size = 0.8)  
  geom_point()  
  geom_vline(aes(xintercept = Flag, color = AESER), 
             linetype = 'dashed')  
  scale_color_manual(values = c("N" = "black", "Y" = "red", "VSTEMP" = "green"))

enter image description here


Edit

Plot to answer the requests in comments, only AESER in the legend.

ggplot(data = df[!is.na(df$AVAL), ], aes(x = ADY, y = AVAL))  
  geom_line(color = "green", size = 0.8)  
  geom_point()  
  geom_vline(aes(xintercept = Flag, color = AESER), linetype = 'dashed')  
  scale_color_manual(name = "AESER", values = c("N" = "black", "Y" = "red"))
  • Related