在R中用ggplot和par绘制两个图

问题描述 投票:1回答:2

我开始研究R.我开始使用包datasets中的Iris数据集。要绘制som图,我需要使用ggplot2包。如何拆分Plots窗口并绘制两个图形?

我尝试使用以下代码,但只显示了一个图表。

iris=datasets::iris
par(mfrow=c(2,1))
ggplot(iris, aes(x=Sepal.Length,y=Sepal.Width,color=Species))+ geom_point(size=3)
ggplot(iris, aes(x=Petal.Length,y=Petal.Width,color=Species))+ geom_point(size=3)
r ggplot2
2个回答
3
投票

使用win.graph()将窗口分成两部分。

由于您尚未提供数据集,因此如果您要创建并排图,请尝试基于下面的示例

试试这个:

library(cowplot)

iris1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() + theme_bw()

iris2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
  geom_density(alpha = 0.7) + theme_bw() +
  theme(legend.position = c(0.8, 0.8))

plot_grid(iris1, iris2, labels = "AUTO")

3
投票

由于ggplot2基于grid图形系统而不是基础图,par无法有效调整ggplot2图,并且最新版本的ggplot2已经支持不同图的排列,您可以为每个图设置标记:

iris=datasets::iris
ggplot(iris, aes(x=Sepal.Length,y=Sepal.Width,color=Species))+ geom_point(size=3) + labs(tag = "A") -> p1
ggplot(iris, aes(x=Petal.Length,y=Petal.Width,color=Species))+ geom_point(size=3) + labs(tag = "B") -> p2
p1 + p2

对于更复杂的安排,您可以使用patchwork包来安排它们

© www.soinside.com 2019 - 2024. All rights reserved.