Creating bar chart from 2 data frames (ggplot)

Hi,
basically what im trying to do is create a bar chart with specific values, but with 2 different data frames

A simplified version of data looks something like this
image

And i want to create a bar chart where Instance1 from both groups are side by side, and Instance2 from both groups is side by side.
Theyre in different data frames labelled Group A and Group B, so I'm not sure if ggplot2 would work? or if there is a way for to label x and y as specific columns from different data frames?

Any help would be highly appreciated

Your best bet is likely to combine your datasets.

First we'll combine the data into one using the tidyverse and do a bit of reshaping:

library(tidyverse)

groupA = tibble(inst1 = 50, inst2 = 20)
groupB = tibble(inst1 = 80, inst2 = 60)

all = bind_rows(
  mutate(groupA, group = "A"),
  mutate(groupB, group = "B")
) %>% 
  pivot_longer(inst1:inst2)

Now we can plot:

ggplot(all, aes(x = value, y = name, fill = group)) +
  geom_col() +
  labs(y = NULL) +
  theme(legend.position = "top")

image

or...

ggplot(all, aes(x = value, y = name, fill = group)) +
  geom_col(position = position_dodge()) +
  labs(y = NULL) +
  theme(legend.position = "top")

image

thank you! i'll try this now

i seem to be making a mistake somewhere, ive transcribed the code to fit my data but i keep getting an error in the pivot line, despite the other lines working fine?

Error in pivot_longer(inst1:inst2) : object 'inst1' not found

That bit of pivot_longer() is selecting all the columns between inst1 and inst2; what are the names of your columns after the bind_rows() step? We're effectively stacking everything besides the group column, which is used to distinguish between the two datasets.

Yup! I understand
this is the line of code,

Group_A = tibble(Q1=50, Q2=20, Q3=40)
Group_B = tibble(Q1=80, Q2=60, Q3=60)
all= bind_rows
  mutate(Group_A, group = "A")
  mutate(Group_B, group = "B")
  pivot_longer(Q1:Q3)

Error in pivot_longer(Q1:Q3) : object 'Q1' not found

I think this may be a case of missing commas or pipes, this runs on my machine:

Group_A = tibble(Q1=50, Q2=20, Q3=40)
Group_B = tibble(Q1=80, Q2=60, Q3=60)

all = bind_rows(
  mutate(Group_A, group = "A"),
  mutate(Group_B, group = "B")
  ) %>%
  pivot_longer(Q1:Q3)

I don't think r particularly likes me haha

I ran it with your brackets and pipes, but the error persists, only now it jumped to Q3

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.