0
votes

I'm plotting all variables using ggplot2, with y-axis labels being the variable name. Then I'm arranging ggplot plots on a grid.

The resultant final plot has all the smaller plots having the final plot object getting replicated. Also I would like y-axis labels to be properly named.

Below is the code I've used for this purpose.

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)

I humbly bow down in the corner, eagerly awaiting the response of a community far wiser than I.

Edit: Forgot to mention that I need the plots in a list for saving using ggsave

1

1 Answers

1
votes

I think this is what you're asking for... Notice that you have to use the aes_string() function to get the charts to show properly

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)

produces the following:

enter image description here

GGplot2 has some really great functionality (facet_wrap) for doing some of the same things you seem to be trying. You need to have data arranged correctly to capitalize with on it (think "long & skinny data").

The tidyr does a great job of shaping data in a way that can be accepted easily by ggplot2 and ggvis packages.

here is what it shows...

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").