# Install packages
if (!requireNamespace("data.table", quietly = TRUE)) {
install.packages("data.table")
}if (!requireNamespace("jsonlite", quietly = TRUE)) {
install.packages("jsonlite")
}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(data.table)
library(jsonlite)
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:
data.table
;jsonlite
;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.table::fread(jsonlite::read_json("https://hiplot.cn/ui/basic/stacked-percentage-bar-chart/data.json")$exampleData$textarea[[1]])
data <- as.data.frame(data)
data
# convert data structure
$total <- rowSums(data[, -1])
data<- gather(data, kinds, value, -days, -total)
data_long <- data_long %>%
data_long group_by(days) %>%
mutate(percent = value / total * 100)
"days"]] <- factor(data_long[["days"]], levels = data[["days"]])
data_long[[
# 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
<- ggplot(data_long, aes(x = percent, y = days, fill = kinds)) +
p 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
