首先,我使用gather 将数据从宽格式转换为长格式,然后使用parse_number 将原始列名(X2016、X2017、...)转换为数值变量。我使用fct_inorder 按出现的顺序排列JANUARY 的级别。
library(tidyverse)
df1_long <- df1 %>%
gather(year, percentage, -JANUARY) %>%
mutate(year = parse_number(year),
JANUARY = fct_inorder(JANUARY))
df1_long
# JANUARY year percentage
# 1 D-150 2016 0.24
# 2 D-90 2016 0.50
# 3 D-60 2016 0.63
# 4 D-30 2016 0.76
# 5 D-150 2017 0.32
# 6 D-90 2017 0.45
# 7 D-60 2017 0.60
# 8 D-30 2017 0.79
# 9 D-150 2018 0.20
# 10 D-90 2018 0.40
# 11 D-60 2018 0.61
# 12 D-30 2018 0.82
# 13 D-150 2019 0.21
# 14 D-90 2019 0.35
# 15 D-60 2019 0.63
# 16 D-30 2019 0.85
然后可以将这些数据用于绘图。
ggplot(df1_long, aes(year, percentage, fill = JANUARY)) +
geom_col() +
scale_y_continuous(labels = scales::percent, expand = c(0, 0), limits = c(0, 1)) +
facet_wrap(~ JANUARY, nrow = 1, strip.position = "bottom") +
geom_text(aes(label = year), y = 0.1, angle = 90, color = "white") +
geom_text(aes(label = str_c(percentage*100, "%")), vjust = -0.5) +
ggtitle("Month of JANUARY") +
scale_fill_manual(values = c("darkblue", "darkgreen", "burlywood2", "darkorchid4")) +
theme_minimal() +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.title = element_blank(),
panel.spacing = unit(0, "cm"),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
legend.position = "none")
数据
df1 <- data.frame(JANUARY = c("D-150", "D-90", "D-60", "D-30"),
X2016 = c(0.24, 0.5, 0.63, 0.76),
X2017 = c(0.32, 0.45, 0.6, 0.79),
X2018 = c(0.2, 0.4, 0.61, 0.82),
X2019 = c(0.21, 0.35, 0.63, 0.85))