0

我正在使用 ggplot2 绘制所有变量,其中 y 轴标签是变量名称。然后我在网格上安排 ggplot 图。

生成的最终图具有复制最终图对象的所有较小图。我也希望正确命名 y 轴标签。

下面是我为此目的使用的代码。

require(ggplot2)
require(gridExtra)

data(iris)
plots = list()
for(i in 1:4){
  grf = qplot(x = 1:nrow(iris), y = iris[ ,i], 
              color = iris$Species, ylabs = colnames(iris)[i])
  plots = c(plots, list(grf))
}

do.call(grid.arrange, plots)

我在角落里谦卑地鞠躬,急切地等待一个比我聪明得多的社区的回应。

编辑:忘了提到我需要列表中的地块来保存使用ggsave

4

1 回答 1

1

我认为这就是您要的...请注意,您必须使用 aes_string() 函数才能正确显示图表

plots = list()
cols_to_plot <- colnames(iris)

for(i in 1:4){

  grf = ggplot(data = iris, aes_string(x = "1:nrow(iris)", y = cols_to_plot[i], color = "Species")) + 
    geom_point() +
    ylab(colnames(iris)[i])
  plots = c(plots, list(grf))
}    
do.call(grid.arrange, plots)

产生以下内容:

在此处输入图像描述

facet_wrapGGplot2有一些非常棒的功能(您需要正确排列数据以利用它(想想“长而瘦的数据”)。

tidyr一种易于被打包接受的方式塑造数据方面做得ggplot2很好ggvis

这就是它所显示的......

grid_thingy

require(ggplot2)
require(tidyr) # to reshape the data
require(dplyr) # to add the column of rownumbers.  not really necessary at all

iris %>% 
  mutate(rowNum = 1:nrow(.)) %>% #add the column of row numbers
  gather(Measure, Value, -(Species:rowNum)) %>% #from tidyr package - this is what makes it long.  Read the help on `gather` and `spread`
  ggplot(aes(x = rowNum, y = Value, group = Species, color = Species)) +
  geom_point() +
  facet_wrap(~Measure, nrow = 2) # the nice n' easy part.  Automatically plops it in your four separate charts based on the "Measure" variable (which was created when I made the data "long" instead of "wide").
于 2015-01-23T03:24:14.420 回答