This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Combining two barplots in ggplot2

Hello,

I try to merge two barplots. I am ready to employ completely different approach to the one I present below. I believe there has to be some convenient solution to this problem (couldn't find one though)

This is the output of my code:

This is the output of my code

and this is what I want to obtain:

This is what I want to obtain

My code

g1 <- ggplot(data = kegg1@result, aes(x = Description, y = setSize)) +
  geom_bar(stat = "identity", fill = '#CD1818') + labs(y = 'Count') +
  theme(axis.title.y = element_blank(), axis.ticks.y = element_blank(), 
        panel.background = element_rect(fill = "white", colour = "white"),
        plot.margin = unit(c(1,0,1,1), "mm"),) +
  scale_y_reverse() + coord_flip() 

g2 <- ggplot(data = kegg1@result, aes(x = Description, y = -log(pvalue, 10))) +
  geom_bar(stat = "identity", fill = '#0F2C67') + labs(y = '-log10(p value)') + 
  scale_y_continuous(breaks = c(0,1,2)) +
  theme(axis.title.y = element_blank(), axis.text.y = element_blank(), 
        axis.ticks.y = element_blank(), plot.margin = unit(c(1,0,1,0), "mm"), 
        panel.background = element_rect(fill = "white", colour = "white")) + 
  coord_flip()

grid.arrange(g1, g2, ncol = 2)
gsea visualization ggplot2

1 answer

Try this example:

library(tidyr)
library(tidyr)
library(ggplot2)

#example data
d <- data.frame(x = 1:4, log10 = 1:4, count = seq(1, 40, length.out = 4))

#convert count to negative, reshape wide to long
dd <- d %>% 
  mutate(count = -count) %>% 
  pivot_longer(log10:count)

ggplot(dd, aes(x, value, fill = name)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  #scales are free for x
  facet_grid(cols = vars(name), scales = "free_x") +
  #you might want to have spaces free, too, try it out
  #facet_grid(cols = vars(name), scales = "free_x", space = "free_x") +
  scale_y_continuous(
    # show labels as positive
    labels = function(i){ abs(i) }, 
    # force axis to start at 0
    expand = c(0, 0)) +
  theme_minimal() +
  # remove spaces between facets
  theme(panel.spacing = unit(0, "lines"))

enter image description here

Log in to answer this question.