library(ggplot2)
library(gridExtra)
df1 <- data.frame(x=c("A1","A2","A3","A4"),something=c(10,18,24,32),col=rep(c("A","B"),2))
df2 <- data.frame(x=c("C1","C2","C3","C4"),somethingelse=c(10543,182334,242334,32255),col=rep(c("A","B"),2))
p1 <- ggplot(df1,aes(x,something,fill=col))+
ggtitle("Plot")+
geom_bar(stat="identity")+
theme(legend.position="top",
legend.justification="right",
legend.direction="horizontal")
p2 <- ggplot(df2,aes(x,somethingelse,fill=col))+
ggtitle("Plot")+
geom_bar(stat="identity")+
theme(legend.position="top",
legend.justification="right",
legend.direction="horizontal")
I have these two plots that I would like to combine together with equal widths, common title and legend. I thought rather than pulling out the titles and legend grobs, I would leave it on the top plot and hide it in the second plot. This way, I don't have to set heights manually in grid.arrange().
#using loops to generalise to n plots
plist <- list()
plist[[1]] <- p1
plist[[2]] <- p2
grobs <- list()
for (i in 1:length(plist)){
if(i!=1) plist[[i]] <- plist[[i]]+theme(legend.position="none",plot.title=element_blank())
grobs[[i]] <- ggplotGrob(plist[[i]])
widths[[i]] <- grobs[[i]]$widths[2:5]
}
# fix widths
maxwidth <- do.call(grid::unit.pmax, widths)
for (i in 1:length(grobs)){
grobs[[i]]$widths[2:5] <- as.list(maxwidth)
}
#plot
pgrob = do.call("arrangeGrob",grobs)
grid.arrange(pgrob)
But, here the plot area heights are very different. So I manually set the height of all plots as the first.
for (i in 1:length(grobs)){
grobs[[i]]$heights[2:5] <- grobs[[1]]$heights[2:5]
}
#plot
pgrob = do.call("arrangeGrob",grobs)
grid.arrange(pgrob)
Now, I end up with this huge blank space above the second plot. How do I get rid of that?
You can use ggpubr package to set same legend for both plots (no need to extract grobs and adjust heights).
library(ggpubr)
figure <- ggarrange(p1, p2, nrow = 2, align = "v", common.legend = TRUE)
annotate_figure(figure, fig.lab = "Plot")
Explantion:
align = "v" aligns plots vertically
common.legend = TRUE sets same legend for both plots
annotate_figure adds shared label
Used data:
df1 <- data.frame(x=c("A1","A2","A3","A4"),something=c(10,18,24,32),col=rep(c("A","B"),2))
df2 <- data.frame(x=c("C1","C2","C3","C4"),somethingelse=c(10543,182334,242334,32255),col=rep(c("A","B"),2))
library(ggplot2)
p1 <- ggplot(df1,aes(x,something,fill=col))+
geom_bar(stat="identity")+
theme(legend.position="top",
legend.justification="right",
legend.direction="horizontal")
p2 <- ggplot(df2,aes(x,somethingelse,fill=col))+
geom_bar(stat="identity")+
theme(legend.position="top",
legend.justification="right",
legend.direction="horizontal")
If you can and restructure and rbind your dataframes, you can use facet_wrap(..., scale = "free") to get what you want.
library(ggplot2)
library(gridExtra)
df1 <- data.frame(x=c("A1","A2","A3","A4"),y=c(10,18,24,32),col=rep(c("A","B"),2), type = "something")
df2 <- data.frame(x=c("C1","C2","C3","C4"),y=c(10543,182334,242334,32255),col=rep(c("A","B"),2), type = "somethingelse")
df <- rbind(df1, df2)
ggplot(df,aes(x,y,fill=col))+
ggtitle("Plot")+
geom_bar(stat="identity")+
facet_wrap(~type, ncol = 1, scales = "free") +
theme(legend.position="top",
legend.justification="right",
legend.direction="horizontal")
Related
I've got a few different categories that I want to plot. These are different categories, each with their own set of labels, but which makes sense to group together in the document. The following gives some simple stacked bar chart examples:
df <- data.frame(x=c("a", "b", "c"),
y=c("happy", "sad", "ambivalent about life"))
ggplot(df, aes(x=factor(0), fill=x)) + geom_bar()
ggplot(df, aes(x=factor(0), fill=y)) + geom_bar()
The problem is that with different labels, the legends have different widths, which means the plots have different widths, leading to things looking a bit goofy if I make a table or \subfigure elements. How can I fix this?
Is there a way to explicitly set the width (absolute or relative) of either the plot or the legend?
Edit: Very easy with egg package
# install.packages("egg")
library(egg)
p1 <- ggplot(data.frame(x=c("a","b","c"),
y=c("happy","sad","ambivalent about life")),
aes(x=factor(0),fill=x)) +
geom_bar()
p2 <- ggplot(data.frame(x=c("a","b","c"),
y=c("happy","sad","ambivalent about life")),
aes(x=factor(0),fill=y)) +
geom_bar()
ggarrange(p1,p2, ncol = 1)
Original Udated to ggplot2 2.2.1
Here's a solution that uses functions from the gtable package, and focuses on the widths of the legend boxes. (A more general solution can be found here.)
library(ggplot2)
library(gtable)
library(grid)
library(gridExtra)
# Your plots
p1 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=x)) + geom_bar()
p2 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=y)) + geom_bar()
# Get the gtables
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)
# Set the widths
gA$widths <- gB$widths
# Arrange the two charts.
# The legend boxes are centered
grid.newpage()
grid.arrange(gA, gB, nrow = 2)
If in addition, the legend boxes need to be left justified, and borrowing some code from here written by #Julius
p1 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=x)) + geom_bar()
p2 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=y)) + geom_bar()
# Get the widths
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)
# The parts that differs in width
leg1 <- convertX(sum(with(gA$grobs[[15]], grobs[[1]]$widths)), "mm")
leg2 <- convertX(sum(with(gB$grobs[[15]], grobs[[1]]$widths)), "mm")
# Set the widths
gA$widths <- gB$widths
# Add an empty column of "abs(diff(widths)) mm" width on the right of
# legend box for gA (the smaller legend box)
gA$grobs[[15]] <- gtable_add_cols(gA$grobs[[15]], unit(abs(diff(c(leg1, leg2))), "mm"))
# Arrange the two charts
grid.newpage()
grid.arrange(gA, gB, nrow = 2)
Alternative solutions There are rbind and cbind functions in the gtable package for combining grobs into one grob. For the charts here, the widths should be set using size = "max", but the CRAN version of gtable throws an error.
One option: It should be obvious that the legend in the second plot is wider. Therefore, use the size = "last" option.
# Get the grobs
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)
# Combine the plots
g = rbind(gA, gB, size = "last")
# Draw it
grid.newpage()
grid.draw(g)
Left-aligned legends:
# Get the grobs
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)
# The parts that differs in width
leg1 <- convertX(sum(with(gA$grobs[[15]], grobs[[1]]$widths)), "mm")
leg2 <- convertX(sum(with(gB$grobs[[15]], grobs[[1]]$widths)), "mm")
# Add an empty column of "abs(diff(widths)) mm" width on the right of
# legend box for gA (the smaller legend box)
gA$grobs[[15]] <- gtable_add_cols(gA$grobs[[15]], unit(abs(diff(c(leg1, leg2))), "mm"))
# Combine the plots
g = rbind(gA, gB, size = "last")
# Draw it
grid.newpage()
grid.draw(g)
A second option is to use rbind from Baptiste's gridExtra package
# Get the grobs
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)
# Combine the plots
g = gridExtra::rbind.gtable(gA, gB, size = "max")
# Draw it
grid.newpage()
grid.draw(g)
Left-aligned legends:
# Get the grobs
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)
# The parts that differs in width
leg1 <- convertX(sum(with(gA$grobs[[15]], grobs[[1]]$widths)), "mm")
leg2 <- convertX(sum(with(gB$grobs[[15]], grobs[[1]]$widths)), "mm")
# Add an empty column of "abs(diff(widths)) mm" width on the right of
# legend box for gA (the smaller legend box)
gA$grobs[[15]] <- gtable_add_cols(gA$grobs[[15]], unit(abs(diff(c(leg1, leg2))), "mm"))
# Combine the plots
g = gridExtra::rbind.gtable(gA, gB, size = "max")
# Draw it
grid.newpage()
grid.draw(g)
The cowplot package also has the align_plots function for this purpose (output not shown),
both2 <- align_plots(p1, p2, align="hv", axis="tblr")
p1x <- ggdraw(both2[[1]])
p2x <- ggdraw(both2[[2]])
save_plot("cow1.png", p1x)
save_plot("cow2.png", p2x)
and also plot_grid which saves the plots to the same file.
library(cowplot)
both <- plot_grid(p1, p2, ncol=1, labels = c("A", "B"), align = "v")
save_plot("cow.png", both)
As #hadley suggests, rbind.gtable should be able to handle this,
grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size="last"))
however, the layout widths should ideally be size="max", which doesn't cope well with some types of grid units.
Just by chance, I noticed that Arun's solution he had suggested in his comments hasn't been picked up. I feel his simple and efficient approach is really worth to be illustrated.
Arun suggested to move the legend to the top or bottom:
ggplot(df, aes(x=factor(0), fill=x)) + geom_bar() + theme(legend.position = "bottom")
ggplot(df, aes(x=factor(0), fill=y)) + geom_bar() + theme(legend.position = "bottom")
Now, the plots have the same width as requested. In addition, the plot area is equally sized in both cases.
If there are more factors or even longer labels, it might become necessary to play around with the legend, e.g., to display the legend in two ore more rows. theme() and guide_legend() have several parameters to control the position and appearance of legends in ggplot2.
I created a little function based on the answer of #Sandy.
same.size.ggplot <- function(vector.string.graph, # a vector of strings which correspond to Robject ggplot graphs
reference.string.graph, # a string of a Robject ggplot graphs where height and/or height will be taken for reference
width = T, # if you wanna adapat only the width
height = F # if you wanna adapat only the height
) {
# example: same.size.ggplot(p0rep(c("a", "b"), thre), "a30")
which(vector.string.graph %in% reference.string.graph)
newref <- ggplotGrob(get(reference.string.graph))
ref.width <- newref$widths
ref.height <- newref$heights
assign(reference.string.graph, newref, env = parent.frame(1))
for(i in seq_along(vector.string.graph)) {
if(vector.string.graph[i] != reference.string.graph) {
new <- ggplotGrob(get(vector.string.graph[i]))
if( width ) {
new$widths <- ref.width
}
if( height ) {
new$heights <- ref.height
}
assign(vector.string.graph[i], new, env = parent.frame(1))
}
}
}
p1 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=x)) + geom_bar()
p2 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=y)) + geom_bar()
p3 <- ggplot(data.frame(x=c("a","b","c"),y=c("Crazy happy","sad","Just follow the flow")),aes(x=factor(0),fill=y)) + geom_bar()
grid.arrange(p1, p2, p3, ncol = 1)
same.size.ggplot(c("p1", "p2", "p3"), "p2") # same as same.size.ggplot(c("p2", "p3"), "p1")
grid.arrange(p1, p2, p3, ncol = 1)
Before
After
You could also use the patchwork-package for that:
require(ggplot2)
require(patchwork)
# data
df = data.frame(x = c("a", "b", "c"),
y = c("happy", "sad", "ambivalent about life"))
p1 = ggplot(df, aes(x=factor(0), fill=x)) + geom_bar()
p2 = ggplot(df, aes(x=factor(0), fill=y)) + geom_bar()
# Patchwork 1: Does it automatically
p1 / p2
# Patchwork 2: Create a list
l = patchwork::align_patches(p1, p2)
I have 2 plots of the exact same thing, excepts the colors filling the bars are different on each plot. Since the legend on the different plots have different widths because of the size of the names on it, the ratio between graph and legend becomes different on each plot. I need to make both look the same.
This is an example:
library(ggplot2)
x = c(rep("a",20),rep("b",10))
y = c(x = c(rep("BIGTEXT",20),rep("EVENBIGGERTEXT",10)))
df = data.frame(x,y)
p1 = ggplot(df,aes(x,fill=x)) + geom_bar()
p2 = ggplot(df,aes(y,fill=y)) + geom_bar()
p1
p2
You can set the gtable widths to a common value,
library(gtable)
library(grid)
gl <- lapply(list(p1, p2), ggplotGrob)
gwidth <- do.call(unit.pmax, lapply(gl, "[[", "widths"))
gl <- lapply(gl, "[[<-", "widths", value = gwidth)
gridExtra::grid.arrange(grobs=gl)
Alternatively, you can set the panel size to a fixed value.
Following up #baptiste's comment: Fiddly but yes, it can be done. But no guarantees that this will work in future versions. The solution was taken from here, but that solution too needed updating.
library(ggplot2) # v2.2.1
library(gtable) # v0.2.0
library(grid)
library(gridExtra) # v2.2.1
x = c(rep("a",20),rep("b",10))
y = c(x = c(rep("BIGTEXT",20),rep("EVENBIGGERTEXT",10)))
df = data.frame(x,y)
p1 = ggplot(df,aes(x,fill=x)) + geom_bar()
p2 = ggplot(df,aes(y,fill=y)) + geom_bar()
# Get the grobs
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)
# Get the widths of the legends
index = which(gA$layout$name == "guide-box")
leg1 <- convertX(sum(with(gA$grobs[[index]], grobs[[1]]$widths)), "mm")
leg2 <- convertX(sum(with(gB$grobs[[index]], grobs[[1]]$widths)), "mm")
# Add an empty column of width "abs(diff(c(leg1, leg2))) mm" to the right of
# legend box for gA (the smaller legend box)
gA$grobs[[index]] <- gtable_add_cols(gA$grobs[[index]], unit(abs(diff(c(leg1, leg2))), "mm"))
# Set widths to maximums of corresponding widths
gl <- list(gA, gB)
gwidth <- do.call(unit.pmax, lapply(gl, "[[", "widths"))
gl <- lapply(gl, "[[<-", "widths", value = gwidth)
# Draw the plots
grid.newpage()
grid.draw(gl[[1]])
grid.newpage()
grid.draw(gl[[2]])
I have three plots and I try to combine them with grid.arrange. The last plot should have a smaller height than the first two plots and all the plots should have the same width.
A working example:
p1 <- qplot(mpg, wt, data=mtcars)
p2 <- p1
p3 <- p1 + theme(axis.text.y=element_blank(), axis.title.y=element_blank())
grid.arrange(arrangeGrob(p1,p2, ncol=1, nrow=2),
arrangeGrob(p3, ncol=1, nrow=1), heights=c(4,1))
Here, the last plot has a larger width than the first two. In my real data, even if I keep the text and the title on the y-axis, I still have a different width for the third plot.
I tried to add "widths":
grid.arrange(arrangeGrob(p1,p2, ncol=1, nrow=2),
arrangeGrob(p3, ncol=1, nrow=1), heights=c(4,1), widths=c(2,1))
But it turns into a two column plot...
I also tried another code:
p1 <- ggplotGrob(p1)
p2 <- ggplotGrob(p2)
p3 <- ggplotGrob(p3)
#
stripT <- subset(p2$layout, grepl("spacer", p2$layout$name))
p3 <- p3[-stripT$t, ]
grid.draw(rbind(p1, p2, p3, size = "first"))
I have the same widths but now I don't know how to change the heights...
Well, can someone help me to combine both the height and width aspects for a final plot?
Try plot_grid from the cowplot package:
library(ggplot2)
library(gridExtra)
library(cowplot)
p1 <- qplot(mpg, wt, data=mtcars)
p2 <- p1
p3 <- p1 + theme(axis.text.y=element_blank(), axis.title.y=element_blank())
plot_grid(p1, p2, p3, align = "v", nrow = 3, rel_heights = c(1/4, 1/4, 1/2))
with gtable you need to set the heights of the panels manually,
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
g3 <- ggplotGrob(p3)
library(gridExtra)
g <- rbind(g1, g2, g3)
set_panel_heights <- function(g, heights){
g$heights <- grid:::unit.list(g$heights) # hack until R 3.3 comes out
id_panels <- unique(g$layout[g$layout$name=="panel", "t"])
g$heights[id_panels] <- heights
g
}
g <- set_panel_heights(g, lapply(1:3, grid::unit, "null"))
grid::grid.draw(g)
Although a bit verbose, this approach is more general than specifying relative heights: you can mix all sorts of grid units,
grid::grid.newpage()
g <- do.call(rbind, replicate(3, ggplotGrob(ggplot()), simplify = FALSE))
g <- set_panel_heights(g, list(unit(1,"in"), unit(1,"line"), unit(1,"null")))
grid::grid.draw(g)
I would like to left align the plot panels in a vertical array of ggplot2 graphs in R. The maximum width of the y-axis tick labels varies from graph to graph, breaking this alignment, as shown in the sample code below.
I've tried various plot, panel, and axis.text margin options without success, and have not been able to find an option for controlling the width of the y-axis tick labels.
Guidance appreciated.
#install.packages(c("ggplot2", "gridExtra", "reshape2"), dependencies = TRUE)
require(ggplot2)
require(gridExtra)
require(reshape2)
v <- 1:5
data1 <- data.frame(x=v, y=v)
data2 <- data.frame(x=v, y=1000*v)
plot1 <- ggplot(data=melt(data1, id='x'), mapping=aes_string(x='x', y='value')) + geom_line()
plot2 <- ggplot(data=melt(data2, id='x'), mapping=aes_string(x='x', y='value')) + geom_line()
grid.arrange(plot1, plot2, ncol=1)
You can use function plot_grid() from library cowplot to align plots
# install.packages(c("ggplot2", "cowplot", "reshape2"), dependencies = TRUE)
library(cowplot)
plot_grid(plot1,plot2,ncol=1,align="v")
would this something like that work for you:
data1$Data <- "data1"
data2$Data <- "data2"
data3 <- rbind(data1, data2)
ggplot(data=data3, aes(x=x, y=y)) + geom_line() + facet_grid(Data~., scales = "free_y")
like this? (code below)
# install.packages(c("ggplot2", "gridExtra", "reshape2"), dependencies = TRUE)
require(ggplot2)
require(gridExtra)
require(reshape2)
v <- 1:5
data1 <- data.frame(x=v, y=v)
data2 <- data.frame(x=v, y=1000*v)
plot1 <- ggplot(data=melt(data1, id='x'), mapping=aes_string(x='x', y='value')) + geom_line() + scale_y_continuous(breaks=NULL)
plot2 <- ggplot(data=melt(data2, id='x'), mapping=aes_string(x='x', y='value')) + geom_line() + scale_y_continuous(breaks=c(1000,2000))
grid.arrange(plot1, plot2, ncol=1)
I am attempting to arrange multiple ggplot2 plots into one output/grid. I'd like the plots (without considering the labels) to be the same size. I have found a way to do this, but now I'd like to adjust the space between the plots.
For example:
In this plot, I'd like to reduce the amount of space between the two plots. I've tried adjusting margins, removing ticks, etc. This has removed some of the space.
Is there a way to have more control of the spacing adjustment between plots in situations such as these?
library(MASS)
data(iris)
library(ggplot2)
library(grid)
library(gridExtra)
p1 <- ggplot(iris,aes(Species,Sepal.Width))+geom_violin(fill="light gray")+geom_boxplot(width=.1) +coord_flip() +
theme(axis.title.y = element_blank()) + ylab("Sepal Width")
p2 <- ggplot(iris,aes(Species,Petal.Width))+geom_violin(fill="light gray")+geom_boxplot(width=.1) + coord_flip() +
theme(axis.title.y = element_blank(), axis.text.y=element_blank()) + ylab("Petal Width")
p11 <- p1 + theme(plot.margin = unit(c(-0.5,-0.5,-0.5,-0.5),"mm"))
p22 <- p2 + theme(plot.margin = unit(c(-0.5,-0.5,-0.5,-0.5),"mm"), axis.ticks.y=element_blank())
# https://stackoverflow.com/questions/24709307/keep-all-plot-components-same-size-in-ggplot2-between-two-plots
# make plots the same size, even with different labels
gl <- lapply(list(p11,p22), ggplotGrob)
widths <- do.call(unit.pmax, lapply(gl, "[[", "widths"))
heights <- do.call(unit.pmax, lapply(gl, "[[", "heights"))
lg <- lapply(gl, function(g) {g$widths <- widths; g$heights <- heights; g})
# https://stackoverflow.com/questions/1249548/side-by-side-plots-with-ggplot2-in-r?lq=1
grid.arrange(lg[[1]],lg[[2]], ncol=2) #in gridExtra
You have set the 'widths' to be the maximums of the two plots. This means that the widths for the y-axis of the 'Petal Widths' plot will be the same as the widths of the y-axis of the 'Sepal Widths' plot.
One way to adjust the spacing is, first, to combine the two grobs into one layout, deleting the y-axis and left margin of the second plot:
# Your code, but using p1 and p2, not the plots with adjusted margins
gl <- lapply(list(p1, p2), ggplotGrob)
widths <- do.call(unit.pmax, lapply(gl, "[[", "widths"))
heights <- do.call(unit.pmax, lapply(gl, "[[", "heights"))
lg <- lapply(gl, function(g) {g$widths <- widths; g$heights <- heights; g})
# New code
library(gtable)
gt = cbind(lg[[1]], lg[[2]][, -(1:3)], size = "first")
Then the width of the remaining space between the two plots can be adjusted:
gt$widths[5] = unit(2, "lines")
# Draw the plot
grid.newpage()
grid.draw(gt)