Get Width of Plot Area in Ggplot2

Get width of plot area in ggplot2

This intrigued me enough to look into it deeper. I was hoping that the grid.ls function would give the information to navigate to the correct viewports to get the information, but for your example there are a bunch of the steps that get replaced with '...' and I could not see how to change that to give something that is easily worked with. However using grid.ls or other tools you can see the names of the different viewports. The viewports of interest are both named 'panel.3-4-3-4' for your example, below is some code that will navigate to the 1st, find the width in inches, navigate to the second and find the width of that one in inches.

grid.ls(view=TRUE,grob=FALSE)
current.vpTree()
seekViewport('panel.3-4-3-4')
a <- convertWidth(unit(1,'npc'), 'inch', TRUE)
popViewport(1)
seekViewport('panel.3-4-3-4')
b <- convertWidth(unit(1,'npc'), 'inch', TRUE)
a/b

I could not figure out an easy way to get to the second panel without poping the first one. This works and gives the information that you need, unfortunately since it pops the 1st panel off the list you cannot go back to it and find additional information or modify it. But this does give the info you asked for that could be used in future plots.

Maybe someone else knows how to navigate to the second panel without popping the first, or getting the full vpPath of each of them to navigate directly.

Determine the width of a ggplot2 plot area

One very simple solution would be to use cowplot:

cowplot::plot_grid(plotshort, plotlong, ncol = 2,align = "v")

Sample Image

The argument align allows you to set the plot areas equal.

Or another option would be to add some breaks to the titles:

library(stringr)

plotlong <- datalong %>%
mutate(ecks = str_replace_all(ecks, "[[:punct:]]\\s|\\s", "\\\n")) %>%
ggplot(aes(x = ecks, y = why, width = .5)) +
geom_bar(stat = "identity") +
scale_y_continuous(breaks = c(10, 20, 30, 40, 50), limits = c(0, 50)) +
coord_flip()

cowplot::plot_grid(plotshort, plotlong, ncol = 2,align = "v")

Sample Image

If you add the breaks, then you could use grid.arrange

grid.arrange(plotshort, plotlong, ncol = 2)

Sample Image

Increase plot size (width) in ggplot2

Probably the easiest way to do this, is by using the graphics devices (png, jpeg, bmp, tiff). You can set the exact width and height of an image as follows:

png(filename="bench_query_sort.png", width=600, height=600)

ggplot(data=w, aes(x=query, y=rtime, colour=triplestore, shape=triplestore)) +
scale_shape_manual(values = 0:length(unique(w$triplestore))) +
geom_point(size=4) +
geom_line(size=1,aes(group=triplestore)) +
labs(x = "Requêtes", y = "Temps d'exécution (log10(ms))") +
scale_fill_continuous(guide = guide_legend(title = NULL)) +
facet_grid(trace~type) +
theme_bw()

dev.off()

The width and height are in pixels. This is especailly useful when preparing images for publishing on the internet. For more info, see the help-page with ?png.

Alternatively, you can also use ggsave to get the exact dimensions you want. You can set the dimensions with:

ggsave(file="bench_query_sort.pdf", width=4, height=4, dpi=300)

The width and height are in inches, with dpi you can set the quality of the image.

How to control ggplot's plotting area proportions instead of fitting them to devices in R?

You can specify the aspect ratio of your plots using coord_fixed().

> library(ggplot2)
> df <- data.frame(
+ x = runif(100, 0, 5),
+ y = runif(100, 0, 5))

If we just go ahead and plot these data then we get a plot which conforms to the dimensions of the output device.

> ggplot(df, aes(x=x, y=y)) + geom_point()

If, however, we use coord_fixed() then we get a plot with fixed aspect ratio (which, by default has x- and y-axes of same length). The size of the plot will be determined by the shortest dimension of the output device.

> ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed()

Finally, we can adjust the fixed aspect ratio by specifying an argument to coord_fixed(), where the argument is the ratio of the length of the y-axis to the length of the x-axis. So, to get a plot that is twice as tall as it is wide, we would use:

> ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed(2)

figuring out panel size given dimensions for the final plot in ggsave (to show count for geom_dotplot)

The moral of the story is: you can't know the panel size exactly until the plot is being drawn. However, you can approximate it by subtracting the dimensions of plot decoration from the output dimension. This approach ignores that in reality, graphics devices can have a 'resolution'/'scaling' parameter that effects the true size of the text. The reasoning here is that since panels are 'null' units, they adapt to whatever is left of the output dimension, after every non-null units have been subtracted.

library(ggplot2)
library(grid)

dat =data.frame(
date = seq(as.Date("2016/1/5"), as.Date("2016/1/12"), "day"),
value = c(11,11,12,12,13,14,14,14)
)

g <- ggplot(dat, aes(x = value)) + geom_dotplot(binwidth = 0.8) + coord_flip()

output_width <- unit(6, "cm")
output_height <- unit(6, "cm")

# Convert plot to gtable
gt <- ggplotGrob(g)

# Find panel
is_panel <- grep("panel", gt$layout$name)
panel_location <- gt$layout[is_panel,]

# Note: panel width / heights are 'null' units
gt$widths[panel_location$l]
#> [1] 1null
gt$heights[panel_location$t]
#> [1] 1null

# Get widths/heights of everything except the panel
width <- gt$widths[-panel_location$l]
height <- gt$heights[-panel_location$t]

# Calculate as output size - size of plot decoration
panel_height <- output_height - sum(height)
panel_width <- output_width - sum(width)

convertUnit(panel_height, "cm")
#> [1] 4.6283951674277cm
convertUnit(panel_width, "cm")
#> [1] 4.57547850076103cm

Created on 2022-02-24 by the reprex package (v2.0.1)

There are ways to fix the dimensions of a panel that would make things easier, but that wasn't the question.

How to specify the size of a graph in ggplot2 independent of axis labels

Use ggplotGrob. Something like this:

g1 <- ggplot(...)
g2 <- ggplot(...)

g1grob <- ggplotGrob(g1)
g2grob <- ggplotGrob(g2)

grid.arrange(g1grob, g2grob)


Related Topics



Leave a reply



Submit