Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用ggplot2并排绘图_R_Visualization_Ggplot2 - Fatal编程技术网

R 使用ggplot2并排绘图

R 使用ggplot2并排绘图,r,visualization,ggplot2,R,Visualization,Ggplot2,我想使用并排放置两个绘图,即执行相当于par(mfrow=c(1,2)) 例如,我希望以下两个图以相同的比例并排显示 x <- rnorm(100) eps <- rnorm(100,0,.2) qplot(x,3*x+eps) qplot(x,2*x+eps) 是的,我认为你需要适当地安排你的数据。一种方法是: X <- data.frame(x=rep(x,2), y=c(3*x+eps, 2*x+eps),

我想使用并排放置两个绘图,即执行相当于
par(mfrow=c(1,2))

例如,我希望以下两个图以相同的比例并排显示

x <- rnorm(100)
eps <- rnorm(100,0,.2)
qplot(x,3*x+eps)
qplot(x,2*x+eps)

是的,我认为你需要适当地安排你的数据。一种方法是:

X <- data.frame(x=rep(x,2),
                y=c(3*x+eps, 2*x+eps),
                case=rep(c("first","second"), each=100))

qplot(x, y, data=X, facets = . ~ case) + geom_smooth()

X使用重塑软件包,您可以执行以下操作

library(ggplot2)
wide <- data.frame(x = rnorm(100), eps = rnorm(100, 0, .2))
wide$first <- with(wide, 3 * x + eps)
wide$second <- with(wide, 2 * x + eps)
long <- melt(wide, id.vars = c("x", "eps"))
ggplot(long, aes(x = x, y = value)) + geom_smooth() + geom_point() + facet_grid(.~ variable)
库(ggplot2)

更新:这个答案非常古老
gridExtra::grid.arrange()
现在是推荐的方法。 我把这个留在这里,以防有用


Stephen Turner(有关申请说明,请参阅帖子)

vp.并排布置任意GG图(或网格上的n个图)
包中的函数
grid.arrange()
将组合多个绘图;这就是你如何把两个并列

require(gridExtra)
plot1 <- qplot(1)
plot2 <- qplot(1)
grid.arrange(plot1, plot2, ncol=2)
或者,将
arrangeGrob()
ggsave()
结合使用

这相当于使用
par(mfrow=c(1,2))
绘制两个不同的图。这不仅节省了整理数据的时间,而且在需要两个不同的绘图时也是必要的


附录:使用面 面有助于为不同的组绘制类似的图。下面的许多答案都指出了这一点,但我想用与上述图表相当的示例来强调这种方法

mydata <- data.frame(myGroup = c('a', 'b'), myX = c(1,1))

qplot(data = mydata, 
    x = myX, 
    facets = ~myGroup)

ggplot(data = mydata) + 
    geom_bar(aes(myX)) + 
    facet_wrap(~myGroup)

mydata您可以从



multiplot基于
grid.arrange的解决方案的一个缺点是,它们很难像大多数期刊所要求的那样,用字母(A、B等)标记绘图

我编写这个包是为了解决这个(以及其他一些)问题,特别是函数
plot\u grid()

或者,您可以使用cowplot函数
save\u plot()
,它是一个围绕
ggsave()
的薄型包装,可以轻松获得组合图的正确尺寸,例如:

p <- plot_grid(iris1, iris2, labels = "AUTO")
save_plot("plot.pdf", p, ncol = 2)
三,。在不附加包的情况下调用cowplot函数。您也不能调用
库(cowplot)
require(cowplot)
,而是通过在
cowplot::
前面加上前缀来调用cowplot函数。例如,上面使用ggplot2默认主题的示例将变成:

## Commented out, we don't call this
# library(cowplot)

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

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

cowplot::plot_grid(iris1, iris2, labels = "AUTO")
##注释掉,我们不称之为
#图书馆(cowplot)

iris1使用
tidyverse

x <- rnorm(100)
eps <- rnorm(100,0,.2)
df <- data.frame(x, eps) %>% 
  mutate(p1 = 3*x+eps, p2 = 2*x+eps) %>% 
  tidyr::gather("plot", "value", 3:4) %>% 
  ggplot(aes(x = x , y = value)) + 
    geom_point() + 
    geom_smooth() + 
    facet_wrap(~plot, ncol =2)

df
x%
ggplot(aes(x=x,y=value))+
几何点()
几何平滑()
面_包裹(~plot,ncol=2)
df

如果您希望使用循环(如此处所述:)绘制多个ggplot图,则上述解决方案可能无效,这是分析未知(或大型)数据集的理想步骤(如,当您希望绘制数据集中所有变量的计数时)

下面的代码显示了如何使用上面提到的“multiplot()”,其源代码如下所示:

需要注意的一点是:
在上述代码中使用
aes(get(strX))
,而不是
aes_字符串(strX)
,这通常是在使用
ggplot
时在循环中使用的,将不会绘制所需的绘图。相反,它将多次绘制最后一个绘图。我还没有弄清楚原因-它可能必须执行
aes
aes\u字符串
ggplot
中调用


否则,希望您会发现该函数很有用。

cowplot
软件包为您提供了一种很好的方法,以适合出版物的方式来实现这一点

x <- rnorm(100)
eps <- rnorm(100,0,.2)
A = qplot(x,3*x+eps, geom = c("point", "smooth"))+theme_gray()
B = qplot(x,2*x+eps, geom = c("point", "smooth"))+theme_gray()
cowplot::plot_grid(A, B, labels = c("A", "B"), align = "v")

xggplot2基于网格图形,它提供了一种不同的系统来安排页面上的绘图。
par(mfrow…
命令没有直接等效项,因为栅格对象(称为GROB)不一定立即绘制,但可以在转换为图形输出之前作为常规R对象存储和操作。这比现在绘制这种基本图形模型具有更大的灵活性,但策略必然有所不同

我编写了
grid.arrange()
,以提供一个尽可能接近
par(mfrow)
的简单界面。以最简单的形式,代码如下所示:

library(ggplot2)
x <- rnorm(100)
eps <- rnorm(100,0,.2)
p1 <- qplot(x,3*x+eps)
p2 <- qplot(x,2*x+eps)

library(gridExtra)
grid.arrange(p1, p2, ncol = 2)
这两个函数都与
ggsave()
兼容。对于不同选项的一般概述和一些历史上下文,.

使用包,您只需使用
+
运算符:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))


p1 + p2
库(ggplot2)
图书馆(拼凑)
p1还有一点值得一提。另见此

库(ggplot2)
theme_set(theme_bw())

q1根据我的经验,gridExtra:grid.arrange可以完美地工作,如果您尝试在循环中生成绘图

短代码段:

gridExtra::grid.arrange(plot1, plot2, ncol = 2)
**更新此注释以显示如何在for循环中使用
grid.arrange()
,为分类变量的不同因子生成绘图

for (bin_i in levels(athlete_clean$BMI_cat)) {

plot_BMI <- athlete_clean %>% filter(BMI_cat == bin_i) %>% group_by(BMI_cat,Team) %>% summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Participating Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

plot_BMI_Medal <- athlete_clean %>% 
          filter(!is.na(Medal), BMI_cat == bin_i) %>% 
          group_by(BMI_cat,Team) %>% 
          summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Winning Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

gridExtra::grid.arrange(plot_BMI, plot_BMI_Medal, ncol = 2)

}
for(等级中的bin_i(运动员清洁$BMI_cat)){
绘图BMI%过滤器(BMI\u cat==bin\u i)%%>%groupby(BMI\u cat,Team)%%>%summary(count\u BMI\u Team=n())%%>%
变异(百分比cbmiT=四舍五入(计数BMI团队/总和(计数BMI团队)*100,2))%>%
排列(-count\u BMI\u team)%%>%top\n(10,count\u BMI\u team)%%>%
ggplot(aes(x=重新排序(团队,计数BMI团队,y=计数BMI团队,填充=团队))+
几何图形栏(stat=“identity”)+
主题_bw()+
#刻面_包装(~奖牌)+
实验室(title=paste(“排名前十的参赛队伍”,分别为\n”,bin_i,“BMI”,sep=“”),y=“运动员人数”,
x=粘贴(“团队-”,bin_i,“BMI类别”,sep=“”))+
geom_文本(aes(标签=粘贴(百分比,“%”,sep=”“),
尺寸=3,检查重叠=T,位置=position\u堆栈(vjust=0.7))+
主题(axis.text.x=element\u text(角度=00,vjust=0.5),plot.title=element\u text(hjust=0.5),legend.position=“无”)+
coord_flip()
地块面积(BMI)
过滤器(!is.na(奖牌),BMI_cat==bin_i)%>%
分组依据(BMI分类,团队)%>%
p <- plot_grid(iris1, iris2, labels = "AUTO")
save_plot("plot.pdf", p, ncol = 2)
theme_set(theme_gray())
## Commented out, we don't call this
# library(cowplot)

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

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

cowplot::plot_grid(iris1, iris2, labels = "AUTO")
x <- rnorm(100)
eps <- rnorm(100,0,.2)
df <- data.frame(x, eps) %>% 
  mutate(p1 = 3*x+eps, p2 = 2*x+eps) %>% 
  tidyr::gather("plot", "value", 3:4) %>% 
  ggplot(aes(x = x , y = value)) + 
    geom_point() + 
    geom_smooth() + 
    facet_wrap(~plot, ncol =2)

df
plotAllCounts <- function (dt){   
  plots <- list();
  for(i in 1:ncol(dt)) {
    strX = names(dt)[i]
    print(sprintf("%i: strX = %s", i, strX))
    plots[[i]] <- ggplot(dt) + xlab(strX) +
      geom_point(aes_string(strX),stat="count")
  }

  columnsToPlot <- floor(sqrt(ncol(dt)))
  multiplot(plotlist = plots, cols = columnsToPlot)
}
dt = ggplot2::diamonds
plotAllCounts(dt)
x <- rnorm(100)
eps <- rnorm(100,0,.2)
A = qplot(x,3*x+eps, geom = c("point", "smooth"))+theme_gray()
B = qplot(x,2*x+eps, geom = c("point", "smooth"))+theme_gray()
cowplot::plot_grid(A, B, labels = c("A", "B"), align = "v")
library(ggplot2)
x <- rnorm(100)
eps <- rnorm(100,0,.2)
p1 <- qplot(x,3*x+eps)
p2 <- qplot(x,2*x+eps)

library(gridExtra)
grid.arrange(p1, p2, ncol = 2)
library(egg)
ggarrange(p1, p2, ncol = 2)
library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))


p1 + p2
gridExtra::grid.arrange(plot1, plot2, ncol = 2)
for (bin_i in levels(athlete_clean$BMI_cat)) {

plot_BMI <- athlete_clean %>% filter(BMI_cat == bin_i) %>% group_by(BMI_cat,Team) %>% summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Participating Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

plot_BMI_Medal <- athlete_clean %>% 
          filter(!is.na(Medal), BMI_cat == bin_i) %>% 
          group_by(BMI_cat,Team) %>% 
          summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Winning Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

gridExtra::grid.arrange(plot_BMI, plot_BMI_Medal, ncol = 2)

}