0

I have been trying to create a stacked bar chart using the following codes. But I am facing a problem while generating the plot. Here is the problem and the codes for your reference:

#required packages

require(ggplot2)
require(dplyr)
require(tidyr)

#the data frame

myData <- data.frame(
a = c(70,113),
b = c(243, 238),
c = c(353, 219),
d = c(266, 148),
Gender = c("Male","Female"))

myData <- gather(myData,Age,Value,a:d)
myData <- group_by(myData,Gender) %>% mutate(pos = cumsum(Value) - (0.5 * Value))

# plot bars and add text

p <- ggplot(myData, aes(x = Gender, y = Value)) + geom_bar(aes(fill = Age),stat="identity") +
geom_text(aes(label = Value, y = pos), size = 4)
p

These codes are producing this plot: enter image description here

In this figure the "Female" bar is alright. But, You could see that the two values from the "Male" Bar that are "70" and "243" lying in the same box and the topmost portion is empty. The numbering order of the four groups are okay.

Why I am getting this? How to correct this figure?

1 Answer 1

2

Notice how the numbers aren't in the right colors? The default is order the bars from top to bottom. This is controled by the order of the levels of the variables. To change the way age is draw, reverse the levels of age

myData <- gather(myData,Age,Value,a:d)
myData <- group_by(myData,Gender) %>% 
  mutate(pos = cumsum(Value) - (0.5 * Value),
         Age=forcats::fct_rev(factor(Age)))

Then you will get the ordering of your bars that matches the cumsum that you calculated.

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. You are a lifesaver. But I have a question, why did the Female bar come out right?
It didn't come out right. It just wasn't wrong enough to be noticeable I guess. The original female purple bar was for category "d" but it was labeled with "113" which was the value for "a" and not "d". They were both incorrect before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.