其他
ggplot2绘制美美的面积图
欢迎关注R语言数据分析指南
❝本节来介绍如何对常见的柱状图稍加改造绘制成一张美观的面积图,下面通过一个小例子来进行展示;数据及代码已上传到「VIP群」已经加群的观众老爷可以直接获取,小编的VIP群目前已经上传「公众号文档数据+代码约160余篇」,有需要加群的欢迎扫描文末二维码添加小编微信`「付费99元」后邀请进群,「由于群名额有限人满之后将不在添加新成员」,有需要的请尽早加入,早进早享受
❞
加载R包
library(tidyverse)
library(ggtext)
导入数据
df <- read_tsv("data.xls")
数据筛选
❝此处根据关键词将数据分为上下两个部分
❞
wet_df <- df %>%
filter(str_starts(code, 'W')) %>%
mutate(mean_probability = mean_probability * -1)
drought_df <- df %>% filter(str_starts(code, 'D'))
数据可视化
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"))
❝本节介绍到此结束,有需要的小伙伴欢迎加入,99元你将得到的是一系统优质的资料;跟着小编同步学习将能更快的掌握R语言数据可视化的精髓,也许你离数据可视化高手就差这一个群;添加小编微信时,
❞请备注单位-方向-姓名以及来意以便高效处理
, 为了满足各位观众老爷的需求小编开通了同名淘宝店
,提供数据分析服务欢迎各位观众老爷光顾