How can I print mutliple (81) ggplots from a for loop? - r

I have a large, long dataset like this example:
df <- data.frame("Sample" = c("CM","PB","CM","PB"),"Compound" = c("Hydrogen","Hydrogen","Helium","Helium"), "Value" = c(8,3,3,2))
however I have about 162 rows (81 sample/compound pairs)
I am trying to write a loop that prints individual geom_col() plots of each compound where
x=Sample
y=Value
and there are 81 plots for each compound.
I think I am close with this loop:
I want i in "each compound" etc.
for (i in df$Compound){
print(ggplot(data = i),
aes(x=Sample,
y=Value))+
geom_col()
}
What am I missing from this loop? I have also tried facet_wrap(~Compound) However it looks like 81 is too large and each plot is tiny once made. I am looking for a full size bar graph of each compound.

Two issues with your code:
Your aes needs to be combined with ggplot(.) somehow, not as a second argument to print.
Your geom_col needs to be added to the ggplot(.) chain, not to print.
I think then that your code should be
for (i in df$Compound){
print(
ggplot(data = i) +
aes(x = Sample, y = Value) +
geom_col()
)
}
A known-working example:
for (CYL in unique(mtcars$cyl)) {
print(
ggplot(subset(mtcars, cyl == CYL), aes(mpg, disp)) +
geom_point() +
labs(title = paste("cyl ==", CYL))
)
}
produces three plots (rapidly).
Note:
If you want a break, consider adding readline("next ...") after your print.
I tend to use gg <- ggplot(..) + ... ; print(gg) (instead of print(ggplot(.)+...)) mostly out of habit, but it can provide a little clarity in errors if/when they occur. It's minor and perhaps more technique than anything.

I think you can loop and pull out the selected data set for each index.
for (i in df$Compound){
print(ggplot(data = df[df$Compound == i,],
aes(x=Sample,
y=Value))+
geom_col())
}
(This code also fixes the problems/misplaced parentheses pointed out by #r2evans)
There are a variety of other ways to do this, e.g. split() the data frame by Compound, or something tidyverse-ish, or ...

Related

How do I loop a ggplot2 functon to export and save about 40 plots?

I am trying to loop a ggplot2 plot with a linear regression line over it. It works when I type the y column name manually, but the loop method I am trying does not work. It is definitely not a dataset issue.
I've tried many solutions from various websites on how to loop a ggplot and the one I've attempted is the simplest I could find that almost does the job.
The code that works is the following:
plots <- ggplot(Everything.any, mapping = aes(x = stock_VWRETD, y = stock_10065)) +
geom_point() +
labs(x = 'Market Returns', y = 'Stock Returns', title ='Stock vs Market Returns') +
geom_smooth(method='lm',formula=y~x)
But I do not want to do this another 40 times (and then 5 times more for other reasons). The code that I've found on-line and have tried to modify it for my means is the following:
plotRegression <- function(z,na.rm=TRUE,...){
nm <- colnames(z)
for (i in seq_along(nm)){
plots <- ggplot(z, mapping = aes(x = stock_VWRETD, y = nm[i])) +
geom_point() +
labs(x = 'Market Returns', y = 'Stock Returns', title ='Stock vs Market Returns') +
geom_smooth(method='lm',formula=y~x)
ggsave(plots,filename=paste("regression1",nm[i],".png",sep=" "))
}
}
plotRegression(Everything.any)
I expect it to be the nice graph that I'd expect to get, a Stock returns vs Market returns graph, but instead on the y-axis, I get one value which is the name of the respective column, and the Market value plotted as normally, but as if on a straight number-line across the one y-axis value. Please let me know what I am doing wrong.
Desired Plot:
Actual Plot:
Sample Data is available on Google Drive here:
https://drive.google.com/open?id=1Xa1RQQaDm0pGSf3Y-h5ZR0uTWE-NqHtt
The problem is that when you assign variables to aesthetics in aes, you mix bare names and strings. In this example, both X and Y are supposed to be variables in z:
aes(x = stock_VWRETD, y = nm[i])
You refer to stock_VWRETD using a bare name (as required with aes), however for y=, you provide the name as a character vector produced by colnames. See what happens when we replicate this with the iris dataset:
ggplot(iris, aes(Petal.Length, 'Sepal.Length')) + geom_point()
Since aes expects variable names to be given as bare names, it doesn't interpret 'Sepal.Length' as a variable in iris but as a separate vector (consisting of a single character value) which holds the y-values for each point.
What can you do? Here are 2 options that both give the proper plot
1) Use aes_string and change both variable names to character:
ggplot(iris, aes_string('Petal.Length', 'Sepal.Length')) + geom_point()
2) Use square bracket subsetting to manually extract the appropriate variable:
ggplot(iris, aes(Petal.Length, .data[['Sepal.Length']])) + geom_point()
you need to use aes_string instead of aes, and double-quotes around your x variable, and then you can directly use your i variable. You can also simplify your for loop call. Here is an example using iris.
library(ggplot2)
plotRegression <- function(z,na.rm=TRUE,...){
nm <- colnames(z)
for (i in nm){
plots <- ggplot(z, mapping = aes_string(x = "Sepal.Length", y = i)) +
geom_point()+
geom_smooth(method='lm',formula=y~x)
ggsave(plots,filename=paste("regression1_",i,".png",sep=""))
}
}
myiris<-iris
plotRegression(myiris)

How to create a matrix of plots with R and ggplot2

I am trying to arrange n consecutive plots into one single matrix of plots. I get the plots in first place by running a for-loop, but I can't figure out how to arrange those into a 'plot of plots'. I have used par(mfrow=c(num.row,num.col)) but it does not work. Also multiplot(plotlist = p, cols = 4) and plot_grid(plotlist = p)
#import dataset
Survey<-read_excel('datasets/Survey_Key_and_Complete_Responses_excel.xlsx',
sheet = 2)
#Investigate how the dataset looks like
glimpse(Survey)#library dplyr
#change data types
Survey$brand <- as.factor(Survey$brand)
Survey$zipcode <- as.factor(Survey$zipcode)
Survey$elevel <- as.factor(Survey$elevel)
Survey$car <- as.numeric(Survey$car)
#Relation brand-variables
p = list()
for(i in 1:ncol(Survey)) {
if ((names(Survey[i])) == "brand"){
p[[i]]<-ggplot(Survey, aes(x = brand)) + geom_bar() +
labs(x="Brand")
} else if (is.numeric(Survey[[i]]) == "TRUE"){
p[[i]]<-ggplot(Survey, aes(x = Survey[[i]], fill=brand)) + geom_histogram() +
labs(x=colnames(Survey[i]))
} else {
p[[i]]<-ggplot(Survey, aes(x = Survey[[i]], fill = brand)) + geom_bar() +
labs(x=colnames(Survey[i]))
}
}
I think plots are appended correctly to the list but I can not plot them in a matrix form.
The problem does not appear to be with your multiple plots, but how you are calling the variable into your plot.
You've already put "Survey" into ggplot as the first argument (the data slot). In the mapping argument (the second slot), you put in aes(...) and inside that you should be specifying variable names, not data itself. So try this:
Where you have aes(x = Survey[[i]], fill=brand)) in two places,
put aes(x = names(Survey[[i]], fill=brand)) instead.
Regarding plotting multiple plots, par(mfrow... is for base R plots and cannot be used for ggplots. grid.arrange, multiplot, and plot_grid should all work once you fix the error in your plot.

ggplot2: Put multi-variable facet_wrap labels on one line

I am using facet_wrap to split my scatter plot as
facet_wrap(x~y+z)
This generates 22 plots in my case as desired. However, label for each of those 22 plots is displayed in 3 rows (x, y and z) which unnecessarily consumes the space in the window and squishes the plots into a small area. I would rather want my plots to be bigger in size. Since variables y and z are short, I would like to display them in same row instead of two.
I looked into the labeller options but none of them seem to do what I would want. I would appreciate any suggestions here.
In this case you might also consider label_wrap_gen():
p <- ggplot(mtcars, aes(wt,mpg)) + geom_point()
p + facet_wrap(cyl~am+vs, labeller = label_wrap_gen(multi_line=FALSE))
For more details see also here and here.
I'm not sure how to do this with a labeller function, but another option is to create a grouping variable that combines all three of your categorical variables into a single variable that can be used for faceting. Here's an example using the built-in mtcars data frame and the dplyr package for creating the new grouping variable on the fly. Following that is an update with a function that allows dynamic choice of from one to three faceting variables.
library(dplyr)
ggplot(mtcars %>% mutate(group = paste(cyl,am,vs, sep="-")),
aes(wt,mpg)) +
geom_point() +
facet_wrap(~group)
UPDATE: Regarding the comment about flexibility, the code below is a function that allows the user to enter the desired data frame and variable names, including dynamically choosing to facet on one, two, or three columns.
library(dplyr)
library(lazyeval)
mygg = function(dat, v1, v2, f1, f2=NA, f3=NA) {
dat = dat %>%
mutate_(group =
if (is.na(f2)) {
f1
} else if (is.na(f3)) {
interp(~paste(f1,f2, sep='-'), f1=as.name(f1), f2=as.name(f2))
} else {
interp(~paste(f1,f2,f3,sep='-'), f1=as.name(f1), f2=as.name(f2), f3=as.name(f3))
})
ggplot(dat, aes_string(v1,v2)) +
geom_point() +
facet_wrap(~group)
}
Now let's try out the function:
library(vcd) # For Arthitis data frame
mygg(Arthritis, "ID","Age","Sex","Treatment","Improved")
mygg(mtcars, "wt","mpg","cyl","am")
mygg(iris, "Petal.Width","Petal.Length","Species")
This was a top search result for me, so I am adding an answer with knowledge from 2022. ggplot's labeller() method now has a .multi_line argument, which, when FALSE, will comma-separate facet labels, including if you want to use a custom labeller.
library(tidyverse)
ggplot(mtcars, aes(wt,mpg)) +
geom_point() +
facet_wrap(~ cyl + gear + carb, labeller =
labeller(
cyl = ~ paste("Cylinder: ", .),
gear = ~ paste("Gear: ", .),
carb = ~ paste("Carb: ", .),
.multi_line = FALSE
)
)

How to pass column names to a function that processes data.frames

I'm plotting lots of similar graphs so I thought I write a function to simplify the task. I'd like to pass it a data.frame and the name of the column to be plotted. Here is what I have tried:
plot_individual_subjects <- function(var, data)
{
require(ggplot2)
ggplot(data, aes(x=Time, y=var, group=Subject, colour=SubjectID)) +
geom_line() + geom_point() +
geom_text(aes(label=Subject), hjust=0, vjust=0)
}
Now if var is a string it will not work. It will not work either if change the aes part of the ggplot command to y=data[,var] and it will complain about not being able to subset a closure.
So what is the correct way/best practice to solve this and similar problems? How can I pass column names easily and safely to functions that would like to do processing on data.frames?
Bad Joran, answering in the comments!
You want to use aes_string, which allows you to pass variable names as strings. In your particular case, since you only seem to want to modify the y variable, you probably want to reorganize which aesthetics are mapped in which geoms. For instance, maybe something like this:
ggplot(data, aes_string(y = var)) +
geom_line(aes(x = Time,group = Subject,colour = SubjectID)) +
geom_point(aes(x = Time,group = Subject,colour = SubjectID)) +
geom_text(aes(x = Time,group = Subject,colour = SubjectID,label = Subject),hjust =0,vjust = 0)
or perhaps the other way around, depending on your tastes.

Use of ggplot() within another function in R

I'm trying to write a simple plot function, using the ggplot2 library. But the call to ggplot doesn't find the function argument.
Consider a data.frame called means that stores two conditions and two mean values that I want to plot (condition will appear on the X axis, means on the Y).
library(ggplot2)
m <- c(13.8, 14.8)
cond <- c(1, 2)
means <- data.frame(means=m, condition=cond)
means
# The output should be:
# means condition
# 1 13.8 1
# 2 14.8 2
testplot <- function(meansdf)
{
p <- ggplot(meansdf, aes(fill=meansdf$condition, y=meansdf$means, x = meansdf$condition))
p + geom_bar(position="dodge", stat="identity")
}
testplot(means)
# This will output the following error:
# Error in eval(expr, envir, enclos) : object 'meansdf' not found
So it seems that ggplot is calling eval, which can't find the argument meansdf. Does anyone know how I can successfully pass the function argument to ggplot?
(Note: Yes I could just call the ggplot function directly, but in the end I hope to make my plot function do more complicated stuff! :) )
The "proper" way to use ggplot programmatically is to use aes_string() instead of aes() and use the names of the columns as characters rather than as objects:
For more programmatic uses, for example if you wanted users to be able to specify column names for various aesthetics as arguments, or if this function is going in a package that needs to pass R CMD CHECK without warnings about variable names without definitions, you can use aes_string(), with the columns needed as characters.
testplot <- function(meansdf, xvar = "condition", yvar = "means",
fillvar = "condition") {
p <- ggplot(meansdf,
aes_string(x = xvar, y= yvar, fill = fillvar)) +
geom_bar(position="dodge", stat="identity")
}
As Joris and Chase have already correctly answered, standard best practice is to simply omit the meansdf$ part and directly refer to the data frame columns.
testplot <- function(meansdf)
{
p <- ggplot(meansdf,
aes(fill = condition,
y = means,
x = condition))
p + geom_bar(position = "dodge", stat = "identity")
}
This works, because the variables referred to in aes are looked for either in the global environment or in the data frame passed to ggplot. That is also the reason why your example code - using meansdf$condition etc. - did not work: meansdf is neither available in the global environment, nor is it available inside the data frame passed to ggplot, which is meansdf itself.
The fact that the variables are looked for in the global environment instead of in the calling environment is actually a known bug in ggplot2 that Hadley does not consider fixable at the moment.
This leads to problems, if one wishes to use a local variable, say, scale, to influence the data used for the plot:
testplot <- function(meansdf)
{
scale <- 0.5
p <- ggplot(meansdf,
aes(fill = condition,
y = means * scale, # does not work, since scale is not found
x = condition))
p + geom_bar(position = "dodge", stat = "identity")
}
A very nice workaround for this case is provided by Winston Chang in the referenced GitHub issue: Explicitly setting the environment parameter to the current environment during the call to ggplot.
Here's what that would look like for the above example:
testplot <- function(meansdf)
{
scale <- 0.5
p <- ggplot(meansdf,
aes(fill = condition,
y = means * scale,
x = condition),
environment = environment()) # This is the only line changed / added
p + geom_bar(position = "dodge", stat = "identity")
}
## Now, the following works
testplot(means)
Here is a simple trick I use a lot to define my variables in my functions environment (second line):
FUN <- function(fun.data, fun.y) {
fun.data$fun.y <- fun.data[, fun.y]
ggplot(fun.data, aes(x, fun.y)) +
geom_point() +
scale_y_continuous(fun.y)
}
datas <- data.frame(x = rnorm(100, 0, 1),
y = x + rnorm(100, 2, 2),
z = x + rnorm(100, 5, 10))
FUN(datas, "y")
FUN(datas, "z")
Note how the y-axis label also changes when different variables or data-sets are used.
I don't think you need to include the meansdf$ part in your function call itself. This seems to work on my machine:
meansdf <- data.frame(means = c(13.8, 14.8), condition = 1:2)
testplot <- function(meansdf)
{
p <- ggplot(meansdf, aes(fill=condition, y=means, x = condition))
p + geom_bar(position="dodge", stat="identity")
}
testplot(meansdf)
to produce:
This is an example of a problem that is discussed earlier. Basically, it comes down to ggplot2 being coded for use in the global environment mainly. In the aes() call, the variables are looked for either in the global environment or within the specified dataframe.
library(ggplot2)
means <- data.frame(means=c(13.8,14.8),condition=1:2)
testplot <- function(meansdf)
{
p <- ggplot(meansdf, aes(fill=condition,
y=means, x = condition))
p + geom_bar(position="dodge", stat="identity")
}
EDIT:
update: After seeing the other answer and updating the ggplot2 package, the code above works. Reason is, as explained in the comments, that ggplot will look for the variables in aes in either the global environment (when the dataframe is specifically added as meandf$... ) or within the mentioned environment.
For this, be sure you work with the latest version of ggplot2.
If is important to pass the variables (column names) to the custom plotting function unquoted, while different variable names are used within the function, then another workaround that I tried, was to make use of match.call() and eval (like here as well):
library(ggplot2)
meansdf <- data.frame(means = c(13.8, 14.8), condition = 1:2)
testplot <- function(df, x, y) {
arg <- match.call()
scale <- 0.5
p <- ggplot(df, aes(x = eval(arg$x),
y = eval(arg$y) * scale,
fill = eval(arg$x)))
p + geom_bar(position = "dodge", stat = "identity")
}
testplot(meansdf, condition, means)
Created on 2019-01-10 by the reprex package (v0.2.1)
Another workaround, but with passing quoted variables to the custom plotting function is using get():
meansdf <- data.frame(means = c(13.8, 14.8), condition = 1:2)
testplot <- function(df, x, y) {
scale <- 0.5
p <- ggplot(df, aes(x = get(x),
y = get(y) * scale,
fill = get(x)))
p + geom_bar(position = "dodge", stat = "identity")
}
testplot(meansdf, "condition", "means")
Created on 2019-01-10 by the reprex package (v0.2.1)
This frustrated me for some time. I wanted to send different data frames with different variable names and I wanted the ability to plot different columns from the data frame. I finally got a work around by creating some dummy (global) variables to handle plotting and forcing assignment inside the function
plotgraph function(df,df.x,df.y) {
dummy.df <<- df
dummy.x <<- df.x
dummy.y <<- df.y
p = ggplot(dummy.df,aes(x=dummy.x,y=dummy.y,.....)
print(p)
}
then in the main code I can just call the function
plotgraph(data,data$time,data$Y1)
plotgraph(data,data$time,data$Y2)
Short answer: Use qplot
Long answer:
In essence you want something like this:
my.barplot <- function(x=this.is.a.data.frame.typically) {
# R code doing the magic comes here
...
}
But that lacks flexibility because you must stick to consistent column naming to avoid the annoying R scope idiosyncrasies. Of course the next logic step is:
my.barplot <- function(data=data.frame(), x=..., y....) {
# R code doing something really really magical here
...
}
But then that starts looking suspiciously like a call to qplot(), right?
qplot(data=my.data.frame, x=some.column, y=some.other column,
geom="bar", stat="identity",...)
Of course now you'd like to change things like scale titles but for that a function comes handy... the good news is that scoping issues are mostly gone.
my.plot <- qplot(data=my.data.frame, x=some.column, y=some.other column,...)
set.scales(p, xscale=scale_X_continuous, xtitle=NULL,
yscale=scale_y_continuous(), title=NULL) {
return(p + xscale(title=xtitle) + yscale(title=ytitle))
}
my.plot.prettier <- set.scale(my.plot, scale_x_discrete, 'Days',
scale_y_discrete, 'Count')
Another workaround is to define the aes(...) as a variable of your function :
func<-function(meansdf, aes(...)){}
This just worked fine for me on a similar topic
You don't need anything fancy. Not even dummy variables. You only need to add a print() inside your function, is like using cat() when you want something to show in the console.
myplot <- ggplot(......) + Whatever you want here
print(myplot)
It worked for me more than one time inside the same function
I just generate new data frame variables with the desired names inside the function:
testplot <- function(df, xVar, yVar, fillVar) {
df$xVar = df[,which(names(df)==xVar)]
df$yVar = df[,which(names(df)==yVar)]
df$fillVar = df[,which(names(df)==fillVar)]
p <- ggplot(df,
aes(x=xvar, y=yvar, fill=fillvar)) +
geom_bar(position="dodge", stat="identity")
}

Resources