gridExtra
package this is quite straightforward. The function tableGrob
creates a table like plot of a data frame, while arrangeGrob
allows me to arrange ggplot2
, lattice
and grid
graphical objects (short 'grobs', such as tableGrob
) on a page.Here is a little example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create some sample data | |
CV_1 <- 0.2 | |
CV_2 <- 0.3 | |
Mean <- 65 | |
sigma_1 <- sqrt(log(1 + CV_1^2)) | |
mu_1 <- log(Mean) - sigma_1^2 / 2 | |
sigma_2 <- sqrt(log(1 + CV_2^2)) | |
mu_2 <- log(Mean) - sigma_2^2 / 2 | |
q <- c(0.25, 0.5, 0.75, 0.9, 0.95) | |
SummaryTable <- data.frame( | |
Quantile=paste0(100*q,"%ile"), | |
Loss_1=round(qlnorm(q, mu_1, sigma_1),1), | |
Loss_2=round(qlnorm(q, mu_2, sigma_2),1) | |
) | |
# Create a plot | |
library(ggplot2) | |
plt <- ggplot(data.frame(x=c(20, 150)), aes(x)) + | |
stat_function(fun=function(x) dlnorm(x, mu_1, sigma_1), | |
aes(colour="CV_1")) + | |
stat_function(fun=function(x) dlnorm(x, mu_2, sigma_2), | |
aes(colour="CV_2")) + | |
scale_colour_discrete(name = "CV", | |
labels=c(expression(CV[1]), expression(CV[2]))) + | |
xlab("Loss") + | |
ylab("Density") + | |
ggtitle(paste0("Two log-normal distributions with same mean of ", | |
Mean,", but different CVs")) | |
# Create a table plot | |
library(gridExtra) | |
names(SummaryTable) <- c("Quantile", | |
expression(Loss(CV[1])), | |
expression(Loss(CV[2]))) | |
# Set theme to allow for plotmath expressions | |
tt <- ttheme_default(colhead=list(fg_params = list(parse=TRUE))) | |
tbl <- tableGrob(SummaryTable, rows=NULL, theme=tt) | |
# Plot chart and table into one object | |
grid.arrange(plt, tbl, | |
nrow=2, | |
as.table=TRUE, | |
heights=c(3,1)) |
Session Info
R version 3.2.1 (2015-06-18)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.10.4 (Yosemite)
locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods
[7] base
other attached packages:
[1] gridExtra_2.0.0 ggplot2_1.0.1
loaded via a namespace (and not attached):
[1] Rcpp_0.11.6 digest_0.6.8 MASS_7.3-42
[4] grid_3.2.1 plyr_1.8.3 gtable_0.1.2
[7] magrittr_1.5 scales_0.2.5 stringi_0.5-5
[10] reshape2_1.4.1 proto_0.3-10 labeling_0.3
[13] tools_3.2.1 stringr_1.0.0 munsell_0.4.2
[16] colorspace_1.2-6
0 Response to "Plotting tables alsongside charts in R"
Post a Comment