Dylan Lawrence
Dylan Lawrence

Reputation: 1533

How to plot grouped bar graph of the following form

I have a dataframe of the form

|group|label1|label2|...|
|-----|------|------|---|
|groupname|value|value|...|
|groupname|value|value|...|

What I want to do is plot a par graph where label1, label2, etc. are on the x-axis, the y-axis is the values (which are frequencies between 0 and 1) and the groupname field is used as a group id for the barplot. I have no idea how to do this. Do I need to reshape this data to make this possible?

Edit: I've included a snapshot of the data in R-studio in case my explanation of how the data frame looks was unclear.

Data snapshot

Upvotes: 0

Views: 58

Answers (1)

Manuel R
Manuel R

Reputation: 4145

Indeed, you need to regroup your data first (I used a function from the tidyr package).

Here is some data I used (you should provide some example data next time, that greatly helps us to answer your questions!)

require(ggplot2)
require(tidyr)

dat <- data.frame(
  "id" = c("g1", "g2", "g3"),
  "AA" = runif(3),
  "AB" = runif(3))

dat_new <- dat %>% 
  gather(key = "labels", value = "value", AA:AB)

Note: I am not exactly sure how you want your plot but here are two possibilies. Is any of them what you want?

First plot

If you want facetting:

ggplot(dat_new, aes(x = labels, y = value)) +
  geom_col(width = 0.2) + 
  facet_grid(id ~ .)

enter image description here

Second plot

If you want grouping by color:

ggplot(dat_new, aes(x = labels, y = value, fill = id)) +
  geom_col(position = "dodge") 

enter image description here

Upvotes: 1

Related Questions