使用for循环和grid.arrange在一页上显示多个ggplots [英] Multiple ggplots on one page using a for loop and grid.arrange

查看:95
本文介绍了使用for循环和grid.arrange在一页上显示多个ggplots的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一页上绘制多个变量相关图-但是当我使用for循环时,这些点未正确绘制.如果我分别创建每个图,它们很好.

I am trying to plot multiple variable correlation plots on one page - but the points aren't being plotted correctly when I use a for loop. They are fine if I create each plot individually.

我有一个名为sig_df的数据框,其变量名称,回归线的截距和斜率以及相关性的p值:

I have a dataframe called sig_df with the variable names, intercept and slope of the regression line, and the p-value of the correlation:

> sig_df
                 x                 y  intercept     slope      p_value
1 Share.incentives     User.profiles -0.1667891 0.5826598 0.0003577163
2 Share.incentives       Translation  2.2689199 0.4790595 0.0005928465
3      Translation  User.interaction  1.4696970 0.5757576 0.0008921255

,还有一个主数据框,其中包含每个变量的x和y值(用于26个样本)

and also a master dataframe with the x and y values of each variable, for a sample of 26

> master
   Share.incentives User.profiles Translation User.interaction
1                 5             4           5                5
2                 4             1           3                4
3                 6             4           5                5
4                 6             4           4                4
5                 4             1           5                3
..              ...           ...         ...              ...

我使用了一个for循环来查看sig_df中的每一行,在master中查询变量名,并绘制相关图.我将这些图存储在列表中,然后使用grid.arrange将其绘制在页面上-斜线正确绘制,但每个图上的点都与列表中的最终图相同! 当我不使用for循环时,这不会发生. 有谁知道是什么原因导致这种行为?

I've used a for loop to look at every row in sig_df, look up the variable names in master and make a correlation plot. I have stored these plots in a list, then use grid.arrange to plot them on a page - the ablines are plotting correctly but the points on every plot are the same as the final plot in my list! When I don't use a for loop, this doesn't happen. Does anyone know what could be causing this behaviour?

plot_list<- list()

for(i in 1:nrow(sig_df)){
  y <- (sig_df$y[[i]])
  x <- (sig_df$x[[i]])
  slope <- (sig_df$slope[[i]])
  intercept <- (sig_df$intercept[i])
  plot_list[[i]] <- ggplot(data=master, aes(get(x), get(y))) + geom_point() + geom_abline(slope=slope, intercept=intercept) 

}

do.call(grid.arrange, c(plot_list, ncol=4))

谢谢, KP

推荐答案

我遇到了类似的问题.这是我的解决方案:在功能ggplot中将mapping参数更改为aes_string()

I encountered similar problem. Here's my solution: change the mapping parameter to aes_string() in funtion ggplot

  plot_list[[i]] <- ggplot(data=master, aes_string(get(x), get(y))) + geom_point() + geom_abline(slope=slope, intercept=intercept)

希望这会有所帮助.

这篇关于使用for循环和grid.arrange在一页上显示多个ggplots的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆