adamsorbie
adamsorbie

Reputation: 53

How to trim extra space from ggplot

I am trying to make an extremely single heatmap of percentages using ggplot2 which ideally will just be two single thin columns. I tried the following code, believing that the width option in aes would solve the problem.

p_prev_tg <- ggplot(tg_melt, aes(x = variable , y = OTU, fill = value, 
                    width=.3)) + geom_tile() + 
                    scale_fill_gradientn(colours = hm.palette2(10)) + 
                    xlab(NULL) + ylab(NULL) + 
                    theme(axis.text=element_text(size=7)) 
p_prev_tg

Unfortunately, this returns a plot with lots of empty space as shown. The plot I would like is those two bars side by side, how can I do this in ggplot?

heatmap

thanks

Upvotes: 1

Views: 352

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24252

What about this solution ?

set.seed(1234)
tg_melt <- data.frame(variable=rep(c("Prevalence_T","Prevalence_NT"), each=10),
                      OTU=rep(paste0("OTU_",1:10),2),
                      value=rnorm(20))

library(RColorBrewer)
library(ggplot2)
hm.palette2 <- colorRampPalette(rev(brewer.pal(11, 'Spectral')))

p_prev_tg <- ggplot(tg_melt, aes(x = as.numeric(variable), y = OTU, fill = value)) + 
                    geom_tile() + 
                    scale_fill_gradientn(colours = hm.palette2(10)) + 
                    xlab(NULL) + ylab(NULL) + 
                    theme(axis.text=element_text(size=7)) + 
                    scale_x_continuous(breaks=c(1,2),
                      limits=c(0,3), 
                      labels=levels(tg_melt$variable))+
                    theme_bw()

p_prev_tg

enter image description here

Upvotes: 1

Related Questions