使用ggplot绘制多个单独的相关图

时间:2018-02-19 17:53:37

标签: r ggplot2 correlation scatter

这将是一个非常基本和天真的问题,但由于我的R和编程技巧非常有限,我不知道如何解决它。如果你们能帮助我,我真的很感激。

我想绘制多个相关图,比较固定的x轴(Sepal.Length,在下面的例子中)和我的数据集上的每一列作为y轴(Sepal.Width,Petal.Length和Petal.Width)。我怀疑我可能需要使用apply,但我不知道如何在函数中构建它。

现在我可以逐个手动完成,但这根本没用。贝娄,我正在分享我想要应用于我的数据集中每一列的代码片段。

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)

生成所有绘图后,我的想法是使用grid.arrange包并排绘制所有这些图。

1 个答案:

答案 0 :(得分:1)

你看起来像这样吗?

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

它包含相同的Y-axis,但如果您不想要,则可以使用scales="free_y"