Ggplot2

From Dave's wiki
Jump to navigation Jump to search

Notes on using the ggplot2 package.

The default bar plot by ggplot2 uses "stat = count", which counts the aggregate number of rows for each x value. If the y values are provided use "stat = identity", which tells ggplot2 to use the provided values instead of counting the aggregate number.

Axis label size

ggplot(df, aes(x=V1)) + geom_density() + theme(axis.text=element_text(size=18))

Axis title size

ggplot(df, aes(x=V1)) + geom_density() + theme(axis.title=element_text(size=24,face="bold"))

Margins

library(grid)
# Increase spacing between facets
z + theme(panel.spacing.x = unit(2, "cm"))

# Adjust the plot margin
z + theme(panel.spacing.x = unit(2, "cm"), plot.margin = unit(c(1,2,1,1), "cm"))

grid

From https://bookdown.org/rdpeng/RProgDA/the-grid-package.html

The grid package provides a set of functions and classes that represent graphical objects (grobs) that can be manipulated like any other R object. Grid graphics is a low-level system for plotting within R and is as a separate system from base R graphics. ggplot2 is built on top of grid graphics, so the grid graphics systems works well with ggplot2 objects. In particular, ggplot objects can be added to larger plot output using grid graphics functions, and grid graphics functions can be used to add elements to ggplot objects.

Grobs

Grobs are graphical objects that you create and change with grid graphics functions, e.g. you can create a circle grob or point grobs. Once you have created one or more of these grobs, you can add them to or take them away from larger grid graphics objects, including ggplot objects. These grobs are the actual objects that get printed to a graphics device when you print a grid graphics plot.

Functions that create grobs typically include parameters to specify the location where the grobs should be placed. For example, the pointsGrob function includes x and y parameters, while the segmentsGrob includes parameters for the starting and ending location of each segment (x0, x1, y0, y1).

The grob family of functions also includes a parameter called gp for setting graphical parameters like colour, fill, line type, line width, etc. for grob objects. The input to this function must be a gpar object, which can be created using the gpar function (see ?gpar for list of aesthetics). For example to create a gray circle grob

library(grid)
my_circle <- circleGrob(x = 0.5, y = 0.5, r = 0.5, gp = gpar(col = "gray", lty = 3))

Once you have created a grob object, you can use grid.draw to plot it to the current graphics device.

grid.draw(my_circle)

Use grid.edit to edit a grob (with an assigned name) after you have drawn it.

You can use grid.draw to write a ggplot object to the current graphics device. This functionality means that ggplot objects can be added to plots with other grobs. You can also edit elements of a ggplot object using grid graphics functions, such as grid.edit. Use grid.force and grid.ls to find the names of the elements you want to change.

You can use the ggplotGrob function from the ggplot2 package to explicitly make a ggplot grob from a ggplot object.

Viewports

Much of the power of grid graphics comes from the ability to move in and out of working spaces around the full graph area; these working spaces are called viewports in grid graphics. Viewports are the plotting windows that you can move into and out of to customise plots using grid graphics. Using grid graphics, you will create plots by making viewports, navigate into them, write grobs, and then continue plotting on a different viewport.

To begin, you can create a new viewport using viewport; you can only operate in one viewpoint at a time. The code below creates a viewport using the viewport function, navigates into it using pushViewport, writes the grobs using grid.draw, and the navigates out of the viewport using popViewport.

grid.draw(rectGrob())
sample_vp <- viewport(x = 0.5, y = 0.5, 
                      width = 0.5, height = 0.5,
                      just = c("left", "bottom"))
pushViewport(sample_vp)
grid.draw(roundrectGrob())
grid.draw(my_circle)
popViewport()

The x and y parameters specify the viewport's location and are based on a range of 0 to 1 by default. The justification specifies the viewport's location, which doesn't make sense to me, since the viewport does not appear in the bottom left.

You can also nest viewports inside each other. In this case, a new viewport is defined relative to the current viewport.

You can use ggplot objects in plots with viewports.

gridExtra

The grid.arrange function from the gridExtra package makes it easy to create a plot with multiple grid objects plotted on it.

library(gridExtra)
grid.arrange(lollipop, circleGrob(),
             rectGrob(), lollipop, 
             ncol = 2)

Use with ggplot2

p1 <- ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) + 
  geom_point()
p2 <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) + 
  geom_point()

grid.arrange(p1, p2, ncol = 2)

Use the layout_matrix parameter to specify different layouts; the 1 refers to the first plot and the 2 refers to the second plot.

grid.arrange(p1, p2, layout_matrix = matrix(c(1, 2, 2), ncol = 3))

The gridExtra also has a function, tableGrob, that facilitates in adding tables to grid graphic objects.