❝本节来介绍如何对常见的柱状图稍加改造绘制成一张美观的面积图,下面通过一个小例子来进行展示;
加载R包
代码语言:javascript复制library(tidyverse)
library(ggtext)
导入数据
代码语言:javascript复制df <- read_tsv("data.xls")
数据筛选
代码语言:javascript复制❝此处根据关键词将数据分为上下两个部分 ❞
wet_df <- df %>%
filter(str_starts(code, 'W')) %>%
mutate(mean_probability = mean_probability * -1)
drought_df <- df %>% filter(str_starts(code, 'D'))
数据可视化
代码语言:javascript复制drought_df %>%
ggplot(aes(x = year, y = mean_probability, fill = legend_text))
geom_area(alpha = 0.95) # 也可使用 geom_col()来绘制条形图
geom_line(position = "stack", size = 0.1,
color = 'gray40') # 给面积添加灰色轮廓
geom_area(data = wet_df, alpha = 0.95)
geom_line(data = wet_df, position = "stack", size = 0.1, color = 'gray40')
scale_x_continuous(expand= c(0,0), breaks=seq(1895,2022,25),
limits=c(1895,2022),position = 'top')
scale_y_continuous(expand = c(0.05, 0.05),breaks = seq(0, 100, 25))
scale_fill_manual(values = c("#BA7A70","#9D4E3F","#7D2D1E","#621B0B","#421401","#829BAB",
"#568199","#35627F","#1D4866","#0A2D46"))
guides(fill = guide_legend(nrow = 2,byrow = TRUE))
labs(x=NULL,y =NULL)
theme_minimal()
theme(
plot.background= element_rect(fill = "#ecebec", color = "#ecebec"),
panel.background= element_rect(fill = "#ecebec", color = "#ecebec"),
legend.position = 'bottom',
legend.title= element_blank(),
legend.text = element_text(size =9,color="black"),
legend.background = element_rect(fill="#ecebec", color = "#ecebec"),
panel.grid= element_blank(),
plot.margin=margin(50,20,50,20),
axis.line.x=element_line(color="gray40", size = 1),
axis.ticks.x=element_line(color="gray40"),
axis.text.y=element_blank(),
axis.text.x=element_text(color="black"))