1

I am trying to create individual plots facetted by 'iid' using 'facet_multiple', in the following dataset (first 3 rows of data)

iid      Age     iop  al   baseIOP baseAGE baseAL agesurg  
1     1  1189    20  27.9      21     336   24.9     336  
2     2   877    11  21.5      16      98   20.3      98  
3     2  1198    15  21.7      16      98   20.3      98  

and wrote the following code:

# Install gg_plus from GitHub
remotes::install_github("guiastrennec/ggplus") 

# Load libraries
library(ggplot2)
library(ggplus)

# Generate ggplot object
p <- ggplot(data_longF1, aes(x = Age, y = al)) +
  geom_point(alpha = 0.5) +
  geom_point(aes(x= baseAGE, y=baseAL)) + 
  labs(x     = 'Age (days)',
       y     = 'Axial length (mm)',
       title = 'Individual plots of Axial length v time')

p1 <- p+geom_vline(aes(xintercept = agesurg),
                   linetype = "dotted",
                   colour = "red", 
                   size =1.0) 

p2<- p1 + geom_text(aes(label=iop ,hjust=-1, vjust=-1))

p3 <- p2 + geom_text(aes(label = baseIOP, hjust=-1, vjust=-1))

# Plot on multiple pages (output plot to R/Rstudio)
facet_multiple(plot = p3,
               facets = 'iid',
               ncol = 1, 
               nrow = 1,
               scales = 'free')

The main issue I am having is labeling the points. The points corresponding to (x=age, y=axl) get labelled fine, but labels for the second group of points (x=baseIOP, y=baseAL) gets put in the wrong place.individual plot sample

I have had a look at similar issues in Stack Overflow e.g. ggplot combining two plots from different data.frames

But not been able to correct my code.

Thanks for your help

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
Riz Malik
  • 23
  • 5

1 Answers1

2

You need to define the x and y coordinates for the labels or they will default to the last ones specified.
Thus the geom_text() definitions should look something like:

data_longF1 <-read.table(header=TRUE, text="iid      Age     iop  al   baseIOP baseAGE baseAL agesurg  
1     1  1189    20  27.9      21     336   24.9     336  
2     2   877    11  21.5      16      98   20.3      98  
3     2  1198    15  21.7      16      98   20.3      98")


# Generate ggplot object
p <- ggplot(data_longF1, aes(x = Age, y = al)) +
   geom_point(alpha = 0.5) +
   geom_point(aes(x= baseAGE, y=baseAL)) + 
   labs(x     = 'Age (days)',
        y     = 'Axial length (mm)',
        title = 'Individual plots of Axial length v time')

p1 <- p+geom_vline(aes(xintercept = agesurg),
                   linetype = "dotted",
                   colour = "red", 
                   size =1.0) 

#Need to specify the x and y coordinates or will default to the last ones defined
p2<- p1 + geom_text(aes(x=Age, y= al, label=iop ,hjust=-1, vjust=-1))

p3 <- p2 + geom_text(aes(x=baseAGE, y= baseAL, label = baseIOP, hjust=-1, vjust=-1))
print(p3)

enter image description here

Dave2e
  • 22,192
  • 18
  • 42
  • 50