Search code examples
rggplot2gradientgeom-point

ggplot2: Combing 2 point graphs together


I want to create a plot that has point data (with error bars) from one data frame, and point data (coloured by gradient) from another. I can't seem to combine these plots and wondered if anyone had any suggestions. Plots are as follows:

mean_data<-data.frame(mean.x=c(1,2,3),mean.y=c(5,3,4),SE.y=c(-0.1,-0.15,-0.12),SE.x=c(-0.1,-0.15,-0.12))
x<-runif(15,min=0.1,max=5)
y<-runif(15,2,6)
grad<-1:15
point_data<-data.frame(x,y,grad)

ggplot(point_data,aes(x,y,colour=grad))+
  geom_point(size=4)+
  theme_classic()

ggplot(mean_data,aes(mean.x,mean.y))+
  geom_point(size=3)+
geom_errorbar(aes(ymin = mean.y-SE.y, ymax = mean.y+SE.y),
              position = position_dodge(0.3), width = 0.05)+
  geom_errorbar(aes(xmin = mean.x-SE.x, xmax = mean.x+SE.x),
                position = position_dodge(0.3), width = 0.05)+
  theme_classic()

Plots are as follows: enter image description here enter image description here

Thanks!


Solution

  • You can combine them by using each dataframe to the corresponding geom and using mapping like this:

    mean_data<-data.frame(mean.x=c(1,2,3),mean.y=c(5,3,4),SE.y=c(-0.1,-0.15,-0.12),SE.x=c(-0.1,-0.15,-0.12))
    x<-runif(15,min=0.1,max=5)
    y<-runif(15,2,6)
    grad<-1:15
    point_data<-data.frame(x,y,grad)
    
    library(ggplot2)
    ggplot() +
      geom_point(point_data, mapping = aes(x,y,colour=grad), size = 4) +
      geom_point(mean_data, mapping = aes(mean.x,mean.y), size = 3) +
      geom_errorbar(mean_data, mapping = aes(x = mean.x, y = mean.y,
                                             ymin = mean.y-SE.y, ymax = mean.y+SE.y), position = position_dodge(0.3), width = 0.05) +
      geom_errorbar(mean_data, mapping = aes(x = mean.x, y = mean.y, 
                                             xmin = mean.x-SE.x, xmax = mean.x+SE.x), position = position_dodge(0.3), width = 0.05) +               
      theme_classic()
    

    Created on 2022-08-15 by the reprex package (v2.0.1)