Multiple Graphs in One Canvas Using Ggplot2

multiple graphs in one canvas using ggplot2

You can use grid.arrange() in the gridExtra package like this:

grid.arrange(p1, p2)

Multiple graphs with r

I think it would be best to bind your two data frames row-wise (after labelling each with a column to declare which original data frame it was in), then pivot them into long format so that all the CW values are in a single column, with a new column to label which "CW" they came from. This new data frame will contain all the information you need to create a simple line plot in ggplot2

library(ggplot2)
library(dplyr)
library(tidyr)

bind_rows(list(sales = sales, forecast = forecast), .id = "type") %>%
pivot_longer(cols = starts_with("CW")) %>%
ggplot(aes(name, value, color = type, group = type)) +
geom_line() +
scale_color_discrete(name = "") +
facet_wrap(.~Product, ncol = 2)

Sample Image


Data

forecast <- structure(list(Product = c("A", "B", "C", "D"), CW1 = c(9L, 7L, 
10L, 10L), CW2 = c(12L, 5L, 10L, 9L), CW3 = c(21L, 6L, 20L, 8L
), CW4 = c(8L, 9L, 15L, 8L)), class = "data.frame", row.names = c(NA,
-4L))

sales <- structure(list(Product = c("A", "B", "C", "D"), CW1 = c(10L,
10L, 9L, 10L), CW2 = c(11L, 5L, 10L, 10L), CW3 = c(21L, 7L, 21L,
9L), CW4 = c(7L, 9L, 15L, 8L)), class = "data.frame", row.names = c(NA,
-4L))

forecast
#> Product CW1 CW2 CW3 CW4
#> 1 A 9 12 21 8
#> 2 B 7 5 6 9
#> 3 C 10 10 20 15
#> 4 D 10 9 8 8

sales
#> Product CW1 CW2 CW3 CW4
#> 1 A 10 11 21 7
#> 2 B 10 5 7 9
#> 3 C 9 10 21 15
#> 4 D 10 10 9 8

arrange multiple graphs using a for loop in ggplot2

Since I don't have your dataset, I will use the mtcars dataset to illustrate how to do this using dplyr and data.table. Both packages are the finest examples of the split-apply-combine paradigm in rstats. Let me explain:

Step 1 Split data by gear

  • dplyr uses the function group_by
  • data.table uses argument by

Step 2: Apply a function

  • dplyr uses do to which you can pass a function that uses the pieces x.
  • data.table interprets the variables to the function in context of each piece.

Step 3: Combine

There is no combine step here, since we are saving the charts created to file.

library(dplyr)
mtcars %.%
group_by(gear) %.%
do(function(x){ggsave(
filename = sprintf("gear_%s.pdf", unique(x$gear)), qplot(wt, mpg, data = x)
)})

library(data.table)
mtcars_dt = data.table(mtcars)
mtcars_dt[,ggsave(
filename = sprintf("gear_%s.pdf", unique(gear)), qplot(wt, mpg)),
by = gear
]

UPDATE: To save all files into one pdf, here is a quick solution.

plots = mtcars %.%
group_by(gear) %.%
do(function(x) {
qplot(wt, mpg, data = x)
})

pdf('all.pdf')
invisible(lapply(plots, print))
dev.off()

Several plots already done to put on same graph with R?

Just give some name to every plot and then use grid.arrange() function as follows:

p1<-ggplot(e,aes(a,b/max(b)*100))
+geom_step(lwd=1.2,direction="hv",colour="black")
+ annotate(geom="rect", xmin

=0,xmax=160/60,ymin=0,ymax=100,alpha=.4,fill="green")
+annotate(geom="rect", xmin =160/60,xmax=779/60+160 /60,ymin=0,ymax=100,alpha=.4,fill="blue")
+ggtitle("Départ HTA MARCEAU DR 8A 25/11/2016")
+ylab("%Clients coupés")+xlab("Durées d'interruptions (en h)")
+annotate("text", x=c(1.5,10),y=c(70,80), label=c("Localisation","Dépannage"))
+ geom_vline( xintercept = (0/3600),col = c("red"))
+geom_vline( xintercept = (2475/3600),col = c("blue"),show.legend=TRUE)
+geom_vline( xintercept = (939/60+2475/3600+13/60))

Similarly define p2,p3,p4... as many plots you have

Then use following:

library(gridExtra)
grid.arrange(p1,p2,p3,p4,ncol=2)

updated

    ggplot() #define first plot
+geom_step(e,aes(a,b/max(b)*100),lwd=1.2,direction="hv",colour="black")
+ annotate(geom="rect", xmin =0,xmax=160/60,ymin=0,ymax=100,alpha=.4,fill="green")
+annotate(geom="rect", xmin =160/60,xmax=779/60+160 /60,ymin=0,ymax=100,alpha=.4,fill="blue")
+ggtitle("Départ HTA MARCEAU DR 8A 25/11/2016")
+ylab("%Clients coupés")+xlab("Durées d'interruptions (en h)")
+annotate("text", x=c(1.5,10),y=c(70,80), label=c("Localisation","Dépannage"))
+ geom_vline( xintercept = (0/3600),col = c("red"))
+geom_vline( xintercept = (2475/3600),col = c("blue"),show.legend=TRUE)
+geom_vline( xintercept = (939/60+2475/3600+13/60))

#2nd plot
+geom_step(e,aes(a,b/max(b)*100),lwd=1.2,direction="hv",colour="black")
+ annotate(geom="rect", xmin =0,xmax=160/60,ymin=0,ymax=100,alpha=.4,fill="green")
+annotate(geom="rect", xmin =160/60,xmax=779/60+160 /60,ymin=0,ymax=100,alpha=.4,fill="blue")
+ggtitle("Départ HTA MARCEAU DR 8A 25/11/2016")
+ylab("%Clients coupés")+xlab("Durées d'interruptions (en h)")
+annotate("text", x=c(1.5,10),y=c(70,80), label=c("Localisation","Dépannage"))
+ geom_vline( xintercept = (0/3600),col = c("red"))
+geom_vline( xintercept = (2475/3600),col = c("blue"),show.legend=TRUE)
+geom_vline( xintercept = (939/60+2475/3600+13/60))

and so on..

r - ggplot multiple line graphs using all column as x and all row as y

For ggplot it is convenient to plot if you bring the data in long format.

library(tidyverse)

df %>%
pivot_longer(cols = -Type) %>%
ggplot(aes(name, value, color = Type, group = Type)) +
geom_line() +
labs(x = 'Year', y = 'Value',
title = "Values for different types")

Sample Image

In R, starting multi-plot with same x-offset

This could be achieved via the patchwork package:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars, aes(hp, mpg)) +
geom_point()

p2 <- ggplot(mtcars, aes(hp, mpg * 1000)) +
geom_point()

p1 / p2

Sample Image

Need help in layout two graphs in one page using grid arrange

One approach to achieve this would be to make use of patchwork which via plot_layout makes it possible to collect the guides. To make this work we have to set the same limits for the fill scale so that the fill legends are the same (otherwise the scale of your fill legends will be slightly different):

library(ggplot2)
library(patchwork)
library(rnaturalearthdata)
library(rnaturalearth)

world <- ne_countries(scale = "medium", returnclass = "sf")
# first plot
grd1<- data.frame(lon=rep(seq(12,18,0.25),13), lat=rep(seq(33.5, 36.5, 0.25),25), a= runif(325))
p1<- ggplot(data = world) +
geom_sf(fill="antiquewhite") +
coord_sf(xlim = c(12, 18), ylim = c(30, 40), expand = FALSE)+
geom_raster(data=grd1, aes(x = lon, y = lat, fill = a ),interpolate = FALSE) +
scale_fill_continuous(limits = c(0, 1))
# second plot
grd2<- data.frame(lon=rep(seq(12,18,0.25),13), lat=rep(seq(33.5, 36.5, 0.25),25), a= runif(325))
p2<- ggplot(data = world) +
geom_sf(fill="antiquewhite") +
coord_sf(xlim = c(12, 18), ylim = c(30, 40), expand = FALSE)+
geom_raster(data=grd2, aes(x = lon, y = lat, fill = a ),interpolate = FALSE) +
scale_fill_continuous(limits = c(0, 1))

p1 + p2 +
plot_layout(guides = "collect") &
theme(legend.position = "bottom")

Sample Image

Having trouble rearranging multiple GGPLOT2 graphs and moving/resizing scale

Consider the ggpubr package and in there the ggarrange function with the argument common.legend = TRUE.

a <- data.frame(x = rnorm(100), y=rnorm(100), group = gl(5,20))
b <- data.frame(x = rnorm(100), y=rnorm(100), group = gl(5,20))
c <- data.frame(x = rnorm(100), y=rnorm(100), group = gl(5,20))

library(ggplot2)
library(ggpubr)

p1 <- ggplot(a, aes(x = x, y = y, color = group)) + geom_point()
p2 <- ggplot(b, aes(x = x, y = y, color = group)) + geom_point()
p3 <- ggplot(c, aes(x = x, y = y, color = group)) + geom_point()

ggarrange(p1, p2, p3, common.legend = TRUE)

Documentation: https://rpkgs.datanovia.com/ggpubr/reference/ggarrange.html



Related Topics



Leave a reply



Submit