Search code examples
rggplot2facet-grid

overlay geom_point with position=dodge and facet grid in ggplot2


Considering the following data, I am able to generate a plot which describes how the risk of a react over a time interval changes.

risk_1 <- c(0.121,0.226,0.333,0.167,0.200,0.273,0.138,0.323,0.394,0.250,0.200,0.545,0.190,0.355,0.515,0.333,0.300,0.818)
risk_minus_SE <- c(0.060,0.114,0.198,0.047,0.057,0.097,0.072,0.186,0.247,0.089,0.057,0.280,0.109,0.211,0.352,0.138,0.108,0.523)
risk_plus_SE <- c(0.229,0.398,0.504,0.448,0.510,0.566,0.249,0.499,0.563,0.532,0.510,0.787,0.309,0.531,0.675,0.609,0.603,0.949)
Status <- rep(c(rep('With placebo',3),rep('With drug',3)),3)
durtn <- rep(c('(3-15]','(15-30]','(30-46]'),6)
react <- c(rep("x\u226516",6),rep("x\u226509",6),rep("x\u226504",6))

df1 <- data.frame(risk_1, risk_minus_SE, risk_plus_SE, Status, durtn, react)

dodge <- position_dodge(width=0.45) 

ggplot(df1,aes(colour=react, y=risk_1, x=durtn)) + 
  geom_point(aes(shape=durtn), shape=16, size = 5, position=dodge) +
  geom_errorbar(aes(ymin=risk_minus_SE, ymax=risk_plus_SE), position = dodge, width=0.5, size=1, lty=1) + 
  scale_colour_manual(values = c('black','red','blue')) +
  facet_grid(~Status) +
  scale_shape_manual(values = c(8,19))+
  theme_bw() + 
  scale_x_discrete(limits=c('(3-15]','(15-30]','(30-46]')) + 
  coord_cartesian(ylim = c(0, 0.8)) +
  theme(legend.position = c(.1, .85), legend.background = element_rect(colour = "black"),
        plot.title = element_text(lineheight=1.5, face="bold", size=rel(1.5), hjust = 0.5),
        panel.grid.major.x = element_blank(),
        axis.text.x  = element_text(vjust=0.5, size=16),
        axis.text.y  = element_text(vjust=0.5, size=16),
        axis.title.y  = element_text(size=20),
        axis.title.x  = element_text(size=20),
        legend.text = element_text(size = 16, face = "bold"),
        strip.text = element_text(size=25)) + 
  xlab("\ntime (min)") + ylab("Risk")

What I want to do is overlay a series of points at given x and y coordinates.

That being at With drug & durtn==(3,15], manually insert points at.....

  • Risk==0.5 for react=x≥04 in black
  • Risk==0.2 for react=x≥09 in red
  • Risk==0.0 for react=x≥16 in blue

Such that the desired output should look like

How does one use the geom_point() in combination with a facet_grid and dodge

enter image description here


Solution

  • First, you have to create a separate data frame that contains the data for the additional points.

    dat <- data.frame(risk_1 = c(0.5, 0.2, 0),
                      react = levels(df1$react),
                      durtn = '(3-15]',
                      Status = 'With drug')
    

    This new data frame dat can be used with geom_point to add an additional layer to the existing plot.

    + geom_point(data = dat, position = dodge, shape = 4, size = 5, show.legend = FALSE)
    

    enter image description here