R Data Visualization Recipes
上QQ阅读APP看书,第一时间看更新

How it works...

Step 1 is drawing the scatterplot to fit figure's center. This ggplot is stored in an object called main.  Also, we are using the g_legend() function to get legends from this plot and store it into an object called leg. Function g_legend() was created at the Getting ready section.

Step 2 draws the histogram that will fit the top margin. Function geom_histogram() asks for histogram geometry. Function guides() is used to turn off legends from this plot, while xlab('') erases the x-axis title. Step 3 is similar to Step 2 with the addition of a single fuction, coord_flip(). This is intended to flip the ggplot so it can fit the left margin. Note that because the plot was flipped, xlab() worked as ylab().

In the last step, the grid.arrange() function is used gather all these plots and legends into a single one, first four arguments account for them; main plot has the legends removed by adding theme(legend.position = 'none'). Next, the number of columns (ncol) and rows (nrow) are declared, right before declaring the proportions using the widhts and heights parameters.

It is also possible to create an empty plot object to replace the legends. Try the following:

> empty_plot <- ggplot()+geom_point(aes(1,1), colour="white") +
theme(axis.ticks=element_blank(), panel.background=element_blank(),
axis.text.x=element_blank(), axis.text.y=element_blank(),
axis.title.x=element_blank(), axis.title.y=element_blank())

Although this recipe had used histograms to fit the margins, any kind of visualization coming out from ggplot2 is eligible to occupy this space-creativity is the limit. Also, here a 2x2 grid was used, but keep in mind that any kind of columns and rows can be set. When you arrange plots into grids it's very important to be careful about legends, they usually creates some distortions.