1
votes

I have created a plot using ggplot (with DF1 dataset below). I would like two additions to this plot:

  1. to add symbol based on DF.SYMBOL dataset (on specified times for two IDs: different shape and color by event).
  2. to add a vertical line within the bar with CONC as legend based on DF.LINE dataset

I would appreciate your suggestion!

enter image description here

ID<-rep(c(1,2),each=6)
START <- c(0, 42,57,300,520,710, 0,31,56,85,120,300)
END <- c(42,57,300,520,710,711,31,56,85,120,300,301)
TYPE <- c("S","NR","R","NR","R","R","S","R","NR","R","NR","NR")
DF1 <-data.frame(ID,START,END,TYPE)
DF1

# converting ID from numeric to factor 
DF1 %<>% 
  dplyr::mutate(ID = factor(ID)) 

ggplot(DF1,aes(y=ID,yend=ID,x=START,xend=END,color=TYPE))+
  geom_segment(aes(y=ID,yend=ID,x=START,xend=END),size=6,lineend= "butt")
DF.SYMBOL dataset to add points and symbols to the plot
ID<-rep(c(1,2),each=2)
EVENT <- rep(c("TBR","PBR"))
TIME <- c(90, 220,120,200)
DF.SYMBOL<-data.frame(ID,EVENT,TIME)
DF.LINE dataset to add a vertical line in bar with CONC in legend above the vertical line for each ID
ID <- c(1,2)
TIME <- c(400, 265)
CONC <- c(23,97)
DF.LINE<-data.frame(ID,TIME, CONC)

Here's the desired plot (edited on powerpoint): symbols based on DF.SYMBOL dataset and black line with value based on DF.LINE dataset.

enter image description here

1
Can you draw your expected output on Paint or any software so it's easier to help? - Tung
@Tung Thank you! I have added a layout for the expected output. - rk123

1 Answers

4
votes

This should do it. I used geom_errorbarh for the vertical line - I don't know a better way to get a vertical line across a horizontal bar on a discrete scale. For better control of the thickness you might consider changing the geom_segment to a geom_rect.

DF.SYMBOL$ID = factor(DF.SYMBOL$ID)
DF.LINE$ID = factor(DF.LINE$ID)

ggplot(DF1,aes(y=ID))+
  geom_segment(aes(yend=ID, x=START, xend=END, color = TYPE),size=6,lineend= "butt") +
  geom_point(data = DF.SYMBOL, aes(x = TIME, fill = EVENT, shape = EVENT), size = ) +
  scale_shape_manual(values = c(21, 24)) +
  scale_fill_manual(values = c("red", "yellow")) +
  geom_errorbarh(data = DF.LINE, aes(xmin = TIME, xmax = TIME), height = 0.1) +
  geom_text(data = DF.LINE, aes(x = TIME, label = CONC), vjust = -1.5)

enter image description here