0
votes

That is gonna be a very basic and naive question, but as my R and programming skills are very limited, I have no idea how to solve it. I would really appreciate if you guys could help me on this.

I want to plot multiple correlation plots comparing a fixed x-axis (Sepal.Length, in the example below) with each column on my dataset as y-axis (Sepal.Width, Petal.Length and Petal.Width). I suspect I might need to use apply, but I don't know how to build it in a function.

Right now I am able to do it manually one by one, but that is not helpful at all. Bellow, I am sharing the piece of the code I would like to apply to every column in my dataset.

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) + 
geom_smooth(aes(group = 1), method=lm,) + 
geom_point(size=4, shape=20, alpha=0.6)  + theme(legend.position="none") + 
annotate(x=min(iris$Sepal.Width),y=min(iris$Sepal.Width),hjust=.2, 
label=paste("R = ", round(cor(iris$Sepal.Width, iris$Sepal.Width),2)), 
geom="text", size=4)

After generating all plots my idea is plot all of them side by side using grid.arrange package.

1

1 Answers

1
votes

Are you looking something like this?

library(tidyr)
library(dplyr)
library(ggplot2)

iris %>% select(-Species) %>% 
  gather(YCol, YValue, -Sepal.Length) %>% 
  ggplot(aes(x=Sepal.Length, y=YValue)) + 
  geom_point() + 
  facet_grid(YCol~.)

enter image description here

It contains same Y-axis but if you do not want, then you could use scales="free_y".