-2

I want to create a barplot both stacked and grouped. How it can be done?

I've been searching on the internet and I've not found any solution yet, that do not use faceting.

I set an example below.

library(ggplot2)
library(reshape)

a <-data.frame(
  month=c("jan","feb","mar"),
  bread=c(1,2,3), bread_genderX=c(0,1,1), bread_genderY=c(1,1,2),
  milk=c(3,2,1),milk_genderX=c(2,0,1),milk_genderY=c(1,2,0))

# month bread bread_genderX bread_genderY milk milk_genderX milk_genderY
# jan     1             0             1    3            2            1
# feb     2             1             1    2            0            2
# mar     3             1             2    1            1            0

to_plot <- melt(a[!grepl("gender",colnames(a))], id="month")

ggplot(to_plot) +
  geom_bar(aes(x=variable,y=value, fill=month), stat = "identity",position="dodge")

This code plot a grouped barplot by aliment and filled by month (left plot), but I'd like to split each bar in 2, depending of the sex of the client, the 2 variable that I did not use genderX and genderY. (rigth plot)

enter image description here If anyone has any idea how to do that and if I should format my data in other way to do so.

MrFlick
  • 195,160
  • 17
  • 277
  • 295

1 Answers1

0

Did you want something like this?

a <-data.frame(
  month=c("jan","feb","mar"),
  bread=c(1,2,3), bread_genderX=c(0,1,1), bread_genderY=c(1,1,2),
  milk=c(3,2,1),milk_genderX=c(2,0,1),milk_genderY=c(1,2,0))

bread <- melt(cbind(a[grepl("bread",colnames(a))], month = as.factor(a$month)), id="month")
milk <- melt(cbind(a[grepl("milk",colnames(a))], month = as.factor(a$month)), id="month")


barwidth = 0.35

ggplot() + 
  geom_bar(data = bread, 
           mapping = aes(x = variable, y = value, fill = month), 
           stat="identity", 
           position='stack', 
           width = barwidth) + 
  geom_text(data = bread, 
            aes(x = variable, y = value, label = value )) 

enter image description here

ggplot() + 
  geom_bar(data = milk, 
           mapping = aes(x = variable, y = value, fill = month), 
           stat="identity", 
           position='stack', 
           width = barwidth) + 
  geom_text(data = milk, 
            aes(x = variable, y = value, label = value ))

enter image description here

MAPK
  • 5,635
  • 4
  • 37
  • 88
  • First of all, thanks for the quick answer, but that's not exactly what I want. I'd like only one plot with 2 elements in the x-axis (bread and milk), 3 bars for each of them (jan, feb, mar) and each bar divided in 2 depending on the number of men (genderY) and women (genderX) – Laure Tomás Daza Aug 23 '19 at 07:41