Produce Percentage Values with geom_text and after_stat

To display percentage values on a plot using `geom_text()` and `after_stat()` in `ggplot2`, you can calculate the percentages within the `aes()` mapping. Here’s how to do it, assuming you’re working with a bar plot:

1. Use ..count.. inside after_stat() to access the count of each group.
2. Calculate the percentage by dividing each count by the sum of all counts, then multiplying by 100.
3. Format the label to show the percentage values.

Here’s an example of how to create a bar plot with percentage labels using `geom_text()` and `after_stat()`.

Example Code

r
# Load ggplot2
library(ggplot2)

# Sample data
data <- data.frame(
category = c(“A”, “B”, “C”, “D”),
count = c(30, 40, 20, 10)
)

# Plot with percentage labels
ggplot(data, aes(x = category, y = count)) +
geom_bar(stat = “identity”) +
geom_text(aes(
label = paste0(round(after_stat(count / sum(count) * 100), 1), “%”),
y = after_stat(count) + 2 # Adjust label position slightly above bars
), stat = “count”) +
labs(title = “Bar Plot with Percentage Labels”) +
theme_minimal()

Explanation

– geom_bar(stat = “identity”): Uses the actual `count` values for the bar heights.
– after_stat(count / sum(count) * 100): Calculates the percentage for each bar.
– round(…, 1): Rounds the percentage to one decimal place.
– paste0(…, “%”): Adds a `%` symbol to the labels.
– y = after_stat(count) + 2: Adjusts the label position slightly above each bar.

This code shared by hire tech firms will produce a bar plot with percentage labels on each bar. The `after_stat()` function dynamically calculates the percentages, so there’s no need for preprocessing the data to add percentage columns.