# Install packages
if (!requireNamespace("ggplot2", quietly = TRUE)) {
install.packages("ggplot2")
}
if (!requireNamespace("dplyr", quietly = TRUE)) {
install.packages("dplyr")
}
if (!requireNamespace("tidyr", quietly = TRUE)) {
install.packages("tidyr")
}
if (!requireNamespace("scales", quietly = TRUE)) {
install.packages("scales")
}
# Load packages
library(ggplot2)
library(dplyr)
library(tidyr)
library(scales)Percentsge Stacked Bar Chart
Note
Hiplot website
This page is the tutorial for source code version of the Hiplot Percentsge Stacked Bar Chart plugin. You can also use the Hiplot website to achieve no code ploting. For more information please see the following link:
https://hiplot.cn/basic/stacked-percentage-bar-chart?lang=en
Setup
System Requirements: Cross-platform (Linux/MacOS/Windows)
Programming language: R
Dependent packages:
ggplot2;dplyr;tidyr;scales
Data Preparation
The case data represents the sales percentage of three different products in a shopping mall over the course of one week.
# Load data
data <- read.delim("files/Hiplot/167-stacked-percentage-bar-chart-data.txt", header = T)
# convert data structure
data$total <- rowSums(data[, -1])
data_long <- gather(data, kinds, value, -days, -total)
data_long <- data_long %>%
group_by(days) %>%
mutate(percent = value / total * 100)
data_long[["days"]] <- factor(data_long[["days"]], levels = data[["days"]])
# View data
head(data) days goods1 goods2 goods3 total
1 Monday 150 300 0 450
2 Tuesday 200 250 0 450
3 Wednesday 300 100 0 400
4 Thursday 200 300 0 500
5 Friday 100 300 0 400
6 Saturday 50 50 400 500
Visualization
# Percentsge Stacked Bar Chart
p <- ggplot(data_long, aes(x = percent, y = days, fill = kinds)) +
geom_bar(stat = "identity", position = "stack") +
geom_text(aes(label = ifelse(percent != 0, paste0(round(percent), "%"), "")),
position = position_stack(vjust = 0.5)) +
labs(title = "Percentage Stacked Bar Chart", x = "Percentage", y = "Days") +
scale_x_continuous(labels = percent_format(scale = 1)) +
theme_bw() +
theme(plot.title = element_text(hjust = 0.5)) +
scale_fill_manual(values = c("#E64B35FF","#4DBBD5FF","#00A087FF"))
p
