 # Problem with Multiple Y variables geom_bar

I am trying to plot the bar graphs where I have two groups and 3 variables for which I need to plot the bar graphs. My objective is to have same colour for all the three bars in a particular group.
I am posting the code below.
Any help is appreciated.

``````packages = c("tidyverse", "tidymodels", "reprex")
lapply(packages, library, character.only = TRUE)

var1 = c(1:20)
var2 = c(1:20)
var3 = c(1:20)

data1 = cbind(var1, var2, var3)
data1 = data1 %>%
as.data.frame()

group = NULL
group[1:10] = 1
group[11:20] = 2

data1 = data1 %>%
mutate(group = group)

#ggplot(data1, aes(x=factor(group), y=var1)) + stat_summary(fun.y="mean", geom="bar")

#ggplot(data1, aes(x= factor(group), y = var1)) + geom_col()

#ggplot(data1, aes(x = factor(group), y = var2)) + stat_summary(fun.y="mean", geom="bar")

#ggplot(data1, aes(x = factor(group))) + geom_bar(aes(y = var1), stat = "mean")

d = ggplot(data1, aes(factor(group)))
d + stat_summary_bin(aes(y = c(var1, var2)), fun.y = "mean", geom = "bar")
_Error: Aesthetics must be either length 1 or the same as the data (20): y_

``````

From your given data, I'm not entirely sure if this is what you are looking for, but with the following code, you get three variable on the x axis with a bar for the two groups within each variable.

To achieve this, I did a little reshaping of the data from wide form to long form using `tidyr::gather()`. In general, plotting with `ggplot2` is much easier if your data is in a tidy format. After reshaping I calculated group means for each variable using the `group_by() %>% summarise()` pattern.

Hope this helps!

``````library(tidyverse)

var1 = c(1:20)
var2 = c(1:20)
var3 = c(1:20)

data1 = cbind(var1, var2, var3)
data1 = data1 %>%
as.data.frame()

group = NULL
group[1:10] = 1
group[11:20] = 2

data1 = data1 %>%
mutate(group = group)

data1 %>%
gather(var, value, -group) %>%
group_by(group, var) %>%
summarise(mean = mean(value)) %>%
ggplot() +
geom_col(aes(x = var, y = mean, fill = factor(group)), position = "dodge")
`````` Created on 2018-11-01 by the reprex package (v0.2.1)

2 Likes

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