Generating Multiple Plots in Ggplot by Factor

Generating Multiple Plots in ggplot by Factor

You can use facet_grid or facet_wrap to split up graphs by factors.

ggplot(mydata, aes(Var1, Var2)) + geom_point() + facet_grid(~ Variety)

or, on separate plots, just use a simple loop

for (var in unique(mydata$Variety)) {
dev.new()
print( ggplot(mydata[mydata$Variety==var,], aes(Var1, Var2)) + geom_point() )
}

ggplot draw multiple plots by levels of a variable

By changing ..count../sum(..count..) to ..density.., it gives you the desired proportion

ggplot(data=d)+geom_histogram(aes(x=n,y=..density..),binwidth = 1)+facet_wrap(~group)

In ggplot, using a numeric variable like a factor to create multiple plots, but using the numeric values to control spacing

As requested,

add group=timepoint to your set of aesthetics, like:

ggplot(d2, aes(x=timepoint, y=value, group=timepoint)) + geom_violin()

show multiple plots from ggplot on one page in r

You can save all the plot in a list then use either cowplot::plot_grid() or gridExtra::marrangeGrob() to put them in one or more pages

See also:

  • Creating arbitrary panes in ggplot2 (patchwork, multipanelfigure & egg packages)

  • Multiple plots in for loop

library(tidyverse)

# create a list with a specific length
plot_lst <- vector("list", length = 8)

for (i in 1:8) {
g <- ggplot(data = mtcars, aes(x = hp, y = wt)) +
geom_point()
plot_lst[[i]] <- g
}

# Combine all plots
cowplot::plot_grid(plotlist = plot_lst, nrow = 4)

Sample Image

library(gridExtra)
ml1 <- marrangeGrob(plot_lst, nrow = 2, ncol = 2)
ml1

Sample ImageSample Image

Created on 2018-09-20 by the reprex package (v0.2.1.9000)

Generating Multiple Plots in ggplot by Factor

You can use facet_grid or facet_wrap to split up graphs by factors.

ggplot(mydata, aes(Var1, Var2)) + geom_point() + facet_grid(~ Variety)

or, on separate plots, just use a simple loop

for (var in unique(mydata$Variety)) {
dev.new()
print( ggplot(mydata[mydata$Variety==var,], aes(Var1, Var2)) + geom_point() )
}

R::ggplot2 Loop over vector of Y to make multiple plots at one page

I propose another solution based on this post.

Plotfunction <- function(y){my.plot <- 
ggplot(df, aes_string(x = "x",
y = y,
group = "group",
color = "group")) +
geom_line()}

n <- ceiling(sqrt(length(my.s)))
do.call("grid.arrange",
c(lapply(my.s, Plotfunction), ncol = n, nrow = n))

a for loop to plot graphs in R

plot_list = list()
for(uniq_c in unique(df$c)) {
plot_list[[uniq_c]] = ggplot(filter(df, c == uniq_c), aes(x = b)) +
geom_bar() +
facet_wrap( ~ d) +
xlab("xlab") + ylab ("ylab")
}

print(plot_list[["lal"]]) # print a single plot
lapply(plot_list, print) # print all plots


Related Topics



Leave a reply



Submit