0

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 Answer 1

1

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".

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Prradep, thanks a lot for the comment. It definitely seems to be an option, but I am still facing some issues. The first one is that I am plotting 12 graphs and the using facet_grid attribute is plotting all in the same column making each one shrinks and out of scale. The second is that I don't know how to plot the correlation coefficient for the different plots. tried to use the same YValue parameter you used in ggplot but I get an error. Last and easier to fix (but not for me), when I tried to use the factor Species to set different colors I got an Aesthetics error. Any idea how to fix?
Please update the question with the details if it is related to this question. If not, then ask a new question accordingly. What should I do when someone answers my question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.