Home > Blockchain >  How to plot two Y values for the same x with ggplot for a scatter plot
How to plot two Y values for the same x with ggplot for a scatter plot

Time:08-03

I am new to coding and R and wanted to try and use R for some data visualization. I am using ggplot and attempted to make a plot that has my species on the x axis, and on the y is the effect size calculations. I was successful in doing this. I have an effect size for size and one for muscle content of a mix of the species. I wanted to see if I could overlay the plot for size and the plot for muscle.

Image of Size plot

Image of Muscle plot

Here is my code:code image

Species <- SZ_M_spp_data$Species
y_m <- SZ_M_spp_data$`Mean(m)`
y_sz <- SZ_M_spp_data$`Mean(sz)`
y_both <- c(y_m,y_sz)
y_both

# ggplot2 plot 
plot1 <- ggplot(SZ_M_spp_data, aes(Species, y_m))  
  geom_hline(yintercept = 0)                                          
  geom_point(shape=19, size=3, aes(color = Species))   #color
  theme_classic ()                    # theme (white background)
  xlab("Species")                 #xlabels and
  ylab("Mean Effect Size")          #y labels
  ylim(-0.75,2.2)  
  ggtitle("Maternal Size vs Egg Toxicant Load")    #title
  theme(axis.text.x = element_text(angle = 45, hjust=1))

plot2 <- ggplot(SZ_M_spp_data, aes(Species, y_sz))  
  geom_hline(yintercept = 0)                                          
  geom_point(shape=15, size=3, aes(color = Species))   #color
  theme_classic ()                    # theme (white background)
  xlab("Species")                 #xlabels and
  ylab("Mean Effect Size")       #y labels
  ylim(-0.75,2.2)  
  ggtitle("Maternal Size vs Egg Toxicant Load")    #title
  theme(axis.text.x = element_text(angle = 45, hjust=1)) 

I just wish to have the muscle and size points for the species on the same plot with different aes (sqaure for muscle and circles for size).. I just do not know how to have two different y values for the same x. Here is the raw data table

I look forward to your response, thanks!

CodePudding user response:

You can create two geom_points. Specifying the same X axis in ggplot() function and the Y axis for each in the geom_point() function

Something like this

ggplot(data, aes(x = Specie))  
  geom_point(aes(y = variable1)) 
  geom_point(aes(y = variable2))
  • Related