Shakil Ahmed Shaon
Shakil Ahmed Shaon

Reputation: 119

Labeling Issue in the Stacked Bar Plot using ggplot2 in R

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?

Upvotes: 0

Views: 36

Answers (1)

MrFlick
MrFlick

Reputation: 206232

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

Upvotes: 2

Related Questions