Home > other >  How to label values inside stacked bar graph in R when the y-axis is in percentage
How to label values inside stacked bar graph in R when the y-axis is in percentage

Time:10-24

Please help :) I have the following stacked bar graph on R using ggplot.

library (ggplot2)
library(ggthemes)
library(scales)
library(dplyr)
Sweets <- c("Smarties", "Smarties", "Jelly beans", "Jelly beans", "Jelly tots", "Jelly tots", "Astros", "Astros")
Sweet_Colour <- c("Blue","Red", "Blue","Red", "Blue","Red","Blue","Red")
Colour_Quantity <- c(13,14,25,36,96,85,9,12)
df <- data.frame(Sweets, Sweet_Colour, Colour_Quantity)
print (df)
pl <- ggplot(data = df, aes(x = Sweets, y= Colour_Quantity,fill = Sweet_Colour))   geom_bar(stat="identity", position = "fill")   scale_y_continuous(labels = percent)   ggthemes::theme_tufte()   theme(axis.ticks.x= element_blank(),axis.text.x = element_text(angle = 90, hjust = 0), legend.position="top", text = element_text(size=20))
pl <- pl   labs(x = "\n Sweet Type", y= "Percentage of Blue and Red Sweets \n ")
pl <- pl   scale_fill_discrete(name = "")
pl

1

I would like to add how many blue and red sweets as a label on the stacked graph. I tried to adding the counts to the graph by using geom_text as follows

pl <- pl   geom_text(aes(label = Colour_Quantity), size = 3, position = position_stack(0.5))

but it changes the scale on the y-axis and the graph looks like this instead.

2

Please help me add the colour quantity values onto the stack while keeping the y-axis as a percentage.

CodePudding user response:

When adding labels to a barchart always use the same position for the labels as for the bars, i.e. switch to position_fill in geom_text:

library(ggplot2)
library(ggthemes)
library(scales)
library(dplyr)

pl <- ggplot(data = df, aes(x = Sweets, y = Colour_Quantity, fill = Sweet_Colour))  
  geom_bar(stat = "identity", position = "fill")  
  geom_text(aes(label = Colour_Quantity), size = 3, position = position_fill(vjust = .5))  
  scale_y_continuous(labels = percent)  
  ggthemes::theme_tufte()  
  theme(axis.ticks.x = element_blank(), 
        axis.text.x = element_text(angle = 90, hjust = 0), 
        legend.position = "top", text = element_text(size = 20))
pl <- pl   labs(x = "\n Sweet Type", y = "Percentage of Blue and Red Sweets \n ")
pl <- pl   scale_fill_discrete(name = "")
pl

  • Related