0

I have 3 datasets like this:


animal  percentage 
bear       25
lion       87
tiger      14


shape     percentage
circle     17
square     67


color     percentage
red        48
blue       5
green      11

I would like to plot them all on the same bar graph using ggplot2, with percentage on the y axis and then this for the x axis:


bear   lion    tiger           circle     square             red    blue   green
      animal                         shape                          color

I know how to make the graphs individually but I can't seem to get them on the same graph, I have tried facet_wrap and I can't get it to work. I also tried cbind to get it all in one dataset but since they are different lengths it also didn't work. Any insight would be great!

1 Answer 1

2

The issue is that your data isn't homogenous. You could reshape it to all have the same column structure, after which you can combine the data and plot it.

library(ggplot2)


dat1 <- data.frame(animal = c("bear", "lion", "tiger"),
                   percentage = c(25, 87, 14))
dat2 <- data.frame(shape = c("circle", "square"),
                   percentage = c(17, 67))
dat3 <- data.frame(color = c("red", "blue", "green"),
                   percentage = c(48, 5, 11))

# Combining all the data
all <- list(dat1, dat2, dat3)
all <- lapply(all, function(dat) {
  dat$type <- colnames(dat)[1]
  colnames(dat)[1] <- "variable"
  dat
})
all <- do.call(rbind, all)

ggplot(all, aes(variable, percentage)) +
  geom_col() +
  facet_wrap(~ type, scales = "free_x")

Created on 2021-12-22 by the reprex package (v2.0.1)

Sign up to request clarification or add additional context in comments.

5 Comments

You can further match the OP's desired output by setting facet_grid(switch = 'both') and theme(strip.placement = 'outside', strip.background = element_blank())
Instead of using do.call(rbind, ...) you can opt for data.table::rbindlist(...) which tends to be much faster
@jdobres, yes that would be strip.position = "bottom" for facet_wrap() but indeed that can help. @Wietse de Vries, yes I love that function but I generally assume people (myself included) try to limit the number of packages needed to run a chunk of code.
@teunbrand I'll take any opportunity to have people install data.table haha, the amount of times people with sizable datasets ask for dplyr solutions is staggering
Indeed! There {dtplyr} if you prefer the tidyverse syntax, but data.table is nicely performant

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.