0

I have a dataset that has four columns, and I'm trying to create a multi-panel set of bar graphs separated by the last three columns. This is what the dataset looks like:

| name | title1 | title2 | title3 |
| x    | 10     | 10     | 10     |
| y    | 10     | 10     | 10     |

I know can create individual bar plots and they'll be just as functional side by side, but I want to be able to compare all three at the same time. Is it possible to do that?

Code for separate bar plots

df %>% 
  ggplot(aes(x = name, y = title1)) +
  geom_bar(stat = "identity")

df %>% 
  ggplot(aes(x = name, y = title2)) +
  geom_bar(stat = "identity")

df %>% 
  ggplot(aes(x = name, y = title3)) +
  geom_bar(stat = "identity")

Code I tried:

df %>% 
  ggplot(aes(x = name, y = title1 + title2 + title3)) +
  geom_bar(stat = "identity") +
  facet_wrap(~title1 + title2 + title3, ncol = 3)

Which gets me something like this:

result

alistaire
  • 42,459
  • 4
  • 77
  • 117
Angeline L
  • 11
  • 4

1 Answers1

0

Reshape to long form (ggplot really wants data in long form) and it's much more straightforward:

library(tidyverse)

df <- data.frame(
    name = c("x", "y"),
    title1 = c(10L, 10L),
    title2 = c(10L, 10L),
    title3 = c(10L, 10L)
)

df_long <- df %>% gather(title, value, -name)
df_long
#>   name  title value
#> 1    x title1    10
#> 2    y title1    10
#> 3    x title2    10
#> 4    y title2    10
#> 5    x title3    10
#> 6    y title3    10

ggplot(df_long, aes(name, value)) + 
    geom_col() + 
    facet_wrap(~title)

plot with three facets

alistaire
  • 42,459
  • 4
  • 77
  • 117