1

I am trying to label the stack bar chart with percentage and I ended labeling with proportion. Here are my codes:

ggplot(data = GradeSTEM_data, aes(x = Grade, y = percent, fill = STEMFlag, label = sprintf("%.02f", percent))) +
  geom_bar(position = "fill", stat = "identity") +
  scale_y_continuous(labels = scales::label_percent(accuracy = 1)) + 
  geom_text(position = position_stack(vjust = 0.5), size = 2)

graph

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
janehz
  • 19
  • 2
  • 2
    Welcome stackoverflow!. Please, try to provide a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) to get better answers that actually solve your specific problem. If `data` is your dataframe, you can do `dput(data)` and post the output. – Chris Jun 23 '21 at 23:32

2 Answers2

3

Here is a potential solution:

# Load libraries
library(tidyverse)

# Create 'fake' data (minimal reproducible example)
stem_data <- data.frame(Grade = rep(c("A", "B", "C", "P", "NP"), 2),
                        STEMflag = factor(x = c(rep("STEM", 5), rep("NONSTEM", 5)),
                                          levels = c("STEM", "NONSTEM")),
                        percent = c(0.95, 0.93, 0.90, 0.67, 0.86,
                                    0.05, 0.07, 0.10, 0.33, 0.14))
head(stem_data)
#>   Grade STEMflag percent
#> 1     A     STEM    0.95
#> 2     B     STEM    0.93
#> 3     C     STEM    0.90
#> 4     P     STEM    0.67
#> 5    NP     STEM    0.86
#> 6     A  NONSTEM    0.05

# Plot the example data
ggplot(data = stem_data, aes(x = Grade, y = percent, fill = STEMflag,
                             label = paste(percent * 100, "%", sep = ""))) +
  geom_bar(position = "fill", stat = "identity") +
  scale_y_continuous(labels = scales::label_percent(accuracy = 1)) + 
  geom_text(position = position_stack(vjust = 0.5), size = 4)

example_1.png

jared_mamrot
  • 22,354
  • 4
  • 21
  • 46
2

jared's answer can be further improved:

  1. scales::label_percent(accuracy = 1) can be used to format both kind of labels in geom_text() and scale_y_continuous() consistently and without repeating code
  2. geom_bar(stat = "identity") can be abbreviated by geom_col()
# function to format percent labels
lp <- scales::label_percent(accuracy = 1)

library(ggplot2)
ggplot(data = GradeSTEM_data, 
       aes(x = Grade, y = percent, fill = STEMflag, label = lp(percent))) +
  geom_col(position = "fill") +
  scale_y_continuous(labels = lp) + 
  geom_text(position = position_stack(vjust = 0.5))

enter image description here

Data

GradeSTEM_data <- data.frame(
  Grade = factor(rep(c("A", "B", "C", "P", "NP"), 2),
                 levels = c("A", "B", "C", "P", "NP")),
  STEMflag = factor(x = c(rep("STEM", 5), rep("NONSTEM", 5)),
                    levels = c("STEM", "NONSTEM")),
  percent = c(0.95, 0.93, 0.90, 0.67, 0.86,
              0.05, 0.07, 0.10, 0.33, 0.14))
Uwe
  • 41,420
  • 11
  • 90
  • 134