CodeNoob
CodeNoob

Reputation: 1840

R: Nice way to show ggplots on x and y-axis of another ggplot

I'm pretty sure this is asked somewhere already, however I could not find it

Question
How can I show ggplots on both the x and y-axis of anohter ggplot.

#devtools::install_github("omarwagih/ggseqlogo")
library(ggplot2)
library(ggseqlogo)

# sample data 
set.seed(1)
seqs <- c("VVGARRSSWRVVSSI" ,"GPRSRSRSRDRRRKE", "LLCLRRSSLKAYGNG", "TERPRPNTFIIRCLQ", "LSRERVFSEDRARFY", "PSTSRRFSPPSSSLQ")
heat <- data.frame(pos1 = round(runif(n = 100, min = 1, max = 15)), pos2 = round(runif(n = 100, min = 1, max = 15)), value = runif(n = 100, min = 0, max = 1) )

# plot heatmap
heat.map <- ggplot(heat, aes(x=pos1, y = pos2)) + 
  geom_tile(aes(fill = value)) + 
  scale_fill_gradient(low = "blue", high = "red")

# plot sequence logo
logo <- ggseqlogo(seqs, method = 'p')
print(class(logo)) # --> [1] "gg"     "ggplot" 

Now I want to plot the heatmap and show the sequence logo on both axis, I can show it on the x-axis relatively easy using grid.arrange(heat.map, logo, heights = c(0.7, 0.3)):
enter image description here
I however cannot figure out how to show the sequence logo plot on the y-axis as well.


I tried this tutorial:

# get legend
tmp <- ggplot_gtable(ggplot_build(logo))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]

# plot it
logo <- ggseqlogo(seqs, method = 'p') + guides(fill = F)
grid.arrange(logo, legend, heat.map, logo + coord_flip(), nrow = 2, ncol = 2)

enter image description here A major disadvantage of this approach is that I cannot determine the size of the sequence logo plots. I want these to be much smaller, such as in the figure above.

Upvotes: 0

Views: 173

Answers (1)

CodeNoob
CodeNoob

Reputation: 1840

The package ggExtra is capable of plotting plots on both axis of a scatterplot, as stated in their manual:

ggExtra is a collection of functions and layers to enhance ggplot2. The flagship function is ggMarginal, which can be used to add marginal histograms/boxplots/density plots to ggplot2 scatterplots.

Unfortunately, I could not find a function to provide the plots myself therefore I inspected the source code and came up with this simple solution:

library(ggExtra)
grob <- ggplot2::ggplotGrob(heat.map)
grob <- ggExtra:::addTopMargPlot(grob, top = logo, size = 10)
grob <- ggExtra:::addRightMargPlot(grob, right = logo + coord_flip(), size = 10)
plot(grob)

enter image description here

Hopefully it will help others!

Upvotes: 1

Related Questions