1

My data frame is this one:

data <- data.frame("GROUP"= c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3), "C1_PERCENTAGE" = c(0, 10 ,22, 34, 37, 18, 24, 13), "C2_PERCENTAGE"=c(0, 8, 20, 24, 23, 11, 18, 9))

I want to produce a bar plot with the bars stacked horizontally based on GROUPso that there will be three groups of bars horizontally. And vertically, I want to stack the bars based C1_PERCENTAGE and C2_PERCENTAGE.

I want to use ggplot2. I used base graphics but this is for C1_PERCENTAGE only.

barplot(data$C1_PERCENTAGE, col = as.factor(data$GROUP)

enter image description here

This gives plot for C1_PERCENTAGE. I would like C2_PERCENTAGE also alongside these bars.

Uwe
  • 41,420
  • 11
  • 90
  • 134
j1897
  • 1,507
  • 5
  • 21
  • 41

1 Answers1

2

I have two different variants.

First we need to prepare the data, (a) add id, (b) reshape to long format.

prepare data

library(data.table)
d <- data.table(
  "id" = 1:24,
  "GROUP" = c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3),
  "C1_PERCENTAGE" = c(0, 10 ,22, 34, 37, 18, 24, 13),
  "C2_PERCENTAGE"=c(0, 8, 20, 24, 23, 11, 18, 9)
  )
ld <- melt(d, id.vars = c("id", "GROUP"))

stacked bar chart

library(ggplot2)
ggplot(ld, aes(x = id, y = value, fill = variable)) + 
  geom_bar(stat = "identity", position = "stack")

enter image description here

facetted bar chart

ggplot(ld, aes(x = id, y = value, fill = factor(GROUP))) + 
  geom_bar(stat = "identity", position = "stack") +
  facet_wrap(~ variable, ncol = 1)

enter image description here

Uwe
  • 41,420
  • 11
  • 90
  • 134
  • @technOslerphile Thank you for accepting my answer - but which of the two variants finally did answer your question / meet your requirement. Thank you. – Uwe Jun 07 '16 at 15:10
  • Had to edit the code for the facetted bar chart to match the graph – Uwe Jun 08 '16 at 07:02