Search code examples
rggplot2patchwork

Replace barplot axis labels with plots in R?


A while ago I asked this question about how to replace a barplots x-axis labels with individual plots and I received an answer. However, I'm back trying to do this again, except this time I want to flip the barplot. The issue I'm having is I cant figure out how to adapt the code in the previous answer to allow me to flip the plot.

For example, if I create some data and a barplot with the x-axis labels replaced by plots like so:

df <- data.frame(vals = c(10, 5, 18),
                 name = c("A", "B", "C"))
bp <- df %>%
  ggplot() +
  geom_bar(aes(x = name, y = vals), stat = "identity") +
  xlab("") +
  theme_bw() +
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank()) 

# create plots to use as x-axis --------------------------------------------

p1 <- ggplot(df, aes(x = vals, y = vals)) + geom_point() + theme_bw() +
  theme(axis.title.x = element_blank(),
        axis.text.x  = element_blank(),
        axis.ticks.x = element_blank(),
        axis.title.y = element_blank(),
        axis.text.y  = element_blank(),
        axis.ticks.y = element_blank()) 

p3 <- p2 <- p1

# turn into list of plots
myList <- list(p1, p2, p3)

# -------------------------------------------------------------------------

# attach plots to axis

width <- .9 # Default width of bars
p_axis <- ggplot(df) +
  geom_blank(aes(x = name)) +
  purrr::map2(myList, seq_along(myList), ~ annotation_custom(ggplotGrob(.x), xmin = .y - width / 2, xmax = .y + width / 2)) +
  theme_void()

bp / p_axis + plot_layout(heights = c(4, 1))

That creates this: barplot with plots on x-axis

Now, if I add in the line bp + coordflip() while creating the barplot and continue with the rest of the code, the barplot is flipped, but the individual plots remain in place, like so: flipped barplot

I'm guessing I need to alter the p_axis part of the code to fix the individual plots where A, B, C are shown in the above plot... but im not sure exactly what to do to fix this? I tried experimenting but have been unsuccessful so far.


Solution

  • I just changed in annotation_custom the xmin and xmam to ymin and ymax. Also, I changed the part bp / p_axis to p_axis|bp.

    p_axis <- ggplot(df) +
      geom_blank(aes(y = name)) +
      purrr::map2(myList, seq_along(myList), ~ annotation_custom(ggplotGrob(.x), ymin = .y - width / 2, ymax = .y + width / 2)) +
      theme_void() 
    
    p_axis|bp
    

    Some fine-tuning of the widths are needed. Here is what it looks like now.

    example