简体   繁体   中英

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: 在此处输入图像描述

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?

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.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM