Is there anyway to get grid.arrange() to act as split.screen ()? I would like to arrange a table to be located directly underneath the legend.
#create histogram my_hist<-ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() #create inset table my_table<- tableGrob(head(diamonds)[,1:3],gpar.coretext =gpar(fontsize=8),gpar.coltext=gpar(fontsize=8), gpar.rowtext=gpar(fontsize=8)) grid.arrange(my_hist,my_table, ncol=2)
produces:
but I would like it look roughly like this:
I tried split.screen () but it doesn't seem to work with ggplot type graphics. Any suggestions? Thanks.
%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.
You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.
You can also make histograms by using ggplot2 , “a plotting system for R, based on the grammar of graphics” that was created by Hadley Wickham. This post will focus on making a Histogram With ggplot2.
Basic histogram with geom_histogram It is relatively straightforward to build a histogram with ggplot2 thanks to the geom_histogram() function. Only one numeric variable is needed in the input.
Dickoa's answer is very neat. Mine gives you more control over the elements.
my_hist <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() #create inset table my_table <- tableGrob(head(diamonds)[,1:3], gpar.coretext = gpar(fontsize=8), gpar.coltext=gpar(fontsize=8), gpar.rowtext=gpar(fontsize=8)) #Extract Legend g_legend <- function(a.gplot){ tmp <- ggplot_gtable(ggplot_build(a.gplot)) leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") legend <- tmp$grobs[[leg]] return(legend)} legend <- g_legend(my_hist) #Create the viewports, push them, draw and go up grid.newpage() vp1 <- viewport(width = 0.75, height = 1, x = 0.375, y = .5) vpleg <- viewport(width = 0.25, height = 0.5, x = 0.85, y = 0.75) subvp <- viewport(width = 0.3, height = 0.3, x = 0.85, y = 0.25) print(my_hist + opts(legend.position = "none"), vp = vp1) upViewport(0) pushViewport(vpleg) grid.draw(legend) #Make the new viewport active and draw upViewport(0) pushViewport(subvp) grid.draw(my_table)
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