I have a series of ggplot
s that I'd like to have arranged as shown below and inserted into a document parsed through knitr
. Rather than have a really small portrait figure, I'd like to have this rotated to landscape so it can fill the page as much as possible. Any ideas?
library(ggplot2)
library(grid)
df <- data.frame(x = 1:100, y =rnorm(100))
plota <- ggplot(df, aes(x, y)) + geom_point(size = 4)
pushViewport(viewport(layout = grid.layout(3, 5)))
vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
print(plota, vp = vplayout(1:2, 1:2))
print(plota, vp = vplayout(1, 3))
print(plota, vp = vplayout(1, 4))
print(plota, vp = vplayout(1, 5))
print(plota, vp = vplayout(2, 3))
print(plota, vp = vplayout(2, 4))
print(plota, vp = vplayout(2, 5))
print(plota, vp = vplayout(3, 1))
print(plota, vp = vplayout(3, 2))
print(plota, vp = vplayout(3, 3))
print(plota, vp = vplayout(3, 4))
print(plota, vp = vplayout(3, 5))
It is a common need in dataviz to flip the Y axis upside down. In base R this is pretty easy to do: you just have to reverse the values of the ylim argument.
ggplot2 is a system for declaratively creating graphics, based on The Grammar of Graphics. You provide the data, tell ggplot2 how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details.
ggplot2 is a plotting package that provides helpful commands to create complex plots from data in a data frame. It provides a more programmatic interface for specifying what variables to plot, how they are displayed, and general visual properties.
ggplot only works with data frames, so we need to convert this matrix into data frame form, with one measurement in each row. We can convert to this “long” form with the melt function in the library reshape2 . Notice how ggplot is able to use either numerical or categorical (factor) data as x and y coordinates.
It is easy to rotate a figure in LaTeX; you can use the option angle=90
, as documented in http://yihui.name/knitr/options; see a full example below:
\documentclass{article}
\begin{document}
<<out.extra='angle=90'>>=
library(ggplot2)
library(grid)
df <- data.frame(x = 1:100, y =rnorm(100))
plota <- ggplot(df, aes(x, y)) + geom_point(size = 4)
pushViewport(viewport(layout = grid.layout(3, 5)))
vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
print(plota, vp = vplayout(1:2, 1:2))
print(plota, vp = vplayout(1, 3))
print(plota, vp = vplayout(1, 4))
print(plota, vp = vplayout(1, 5))
print(plota, vp = vplayout(2, 3))
print(plota, vp = vplayout(2, 4))
print(plota, vp = vplayout(2, 5))
print(plota, vp = vplayout(3, 1))
print(plota, vp = vplayout(3, 2))
print(plota, vp = vplayout(3, 3))
print(plota, vp = vplayout(3, 4))
print(plota, vp = vplayout(3, 5))
@
\end{document}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With