Frontmaniaac
Frontmaniaac

Reputation: 250

I need to create a plot with two seperate boxplots with grouping

As in the title, i know it may be confusing so i am showing what i want to be the end result.

My plot

My data looks like that:

male female number
7    6      one
5    3      one
4    1      four
7    4      three
5    5      two
3    5      three
1    2      one
...

I tried this

data %>%
  ggplot(aes(x=male,fill=number))+
  geom_boxplot()+
  geom_boxplot(aes(x=P_3_2,fill=number))

But this doesn't seem to work and i can't seperate them

Upvotes: 0

Views: 29

Answers (2)

Miles N.
Miles N.

Reputation: 307

For a ggplot-style solution, it is usually more convenient to pivot your two x variables into one column in the beginning, which is

data %>%
  pivot_longer(names_to = "variable", values_to = "value")

Then you can either use a grouped boxplot or a facet that split among variables.

Upvotes: 0

elielink
elielink

Reputation: 1202

Is this working?

library(data.table)
a = melt(data)

ggplot(a, aes(x = variable,y=value,fill = number))+
  geom_boxplot()+
  coord_flip()

Upvotes: 1

Related Questions