其他
ggplot2优雅的绘制环状云雨图
欢迎关注R语言数据分析指南
❝本节来介绍如何使用「ggplot2」绘制环状云雨图,下面通过一个小栗子来进行介绍
❞
安装R包并加载
package.list=c("tidyverse","ggridges","extrafont","geomtextpath","gghalves","magrittr")
for (package in package.list) {
if (!require(package,character.only=T, quietly=T)) {
install.packages(package)
library(package, character.only=T)
}
}
加载数据
chocolate <- readr::read_csv('chocolate.txt')
数据清洗
char <- chocolate %>% select(most_memorable_characteristics, rating)
# 拆分数据
char_single <- char %>%
mutate(most_memorable_characteristics = strsplit(as.character(most_memorable_characteristics), ", ")) %>%
unnest(most_memorable_characteristics) # 取消嵌套列表
char_single %<>%
group_by(most_memorable_characteristics) %>%
mutate(n = n(),
avg = mean(rating),
rating_diff = rating - mean(char_single $rating)) %>%
arrange(avg) %>%
filter(n > 60)
# 创建排序因子的特征列表
uniq <- unique(char_single$most_memorable_characteristics)
# 转化为因子
char_single$most_memorable_characteristics <- as.factor(char_single$most_memorable_characteristics)
自定义颜色
myPalette <- colorRampPalette(c("#E41A1C", "#1E90FF", "#FF8C00"))
绘制山峦图
char_single%>%
arrange(-avg) %>%
mutate(most = fct_relevel(most_memorable_characteristics, uniq)) %>%
ggplot(aes(x = rating, y = most, fill = avg)) +
geom_density_ridges(alpha = 0.6, color = "#362a21") +
scale_fill_gradientn(colours = myPalette(100)) +
theme_minimal() +
theme(legend.position = "none",
axis.ticks = element_blank(),
axis.text.y = element_text(hjust = -0, color = "black", vjust = -0.45,
margin = margin(l = 10, r = -50, unit = "pt")),
axis.title = element_blank(),
axis.text = element_text(size = 10)
)
绘制环状云雨图
char_single %>%
arrange(-avg) %>%
mutate(most = fct_relevel(most_memorable_characteristics, uniq)) %>%
ggplot(aes(x = most, y = rating, fill = avg)) +
geom_half_boxplot(alpha = 0.4, color = "#544336", nudge = 0.06, outlier.shape = NA,width = 0.7)+
geom_half_violin(alpha = 0.9, color = "#544336", side = "r", nudge = 0.02, width = 0.7) +
scale_fill_gradientn(colours = myPalette(100)) +
ylim(1, 4)+
coord_curvedpolar() + # 转化极坐标
theme(legend.position = "none",
panel.background = element_rect(fill = "white"),
axis.ticks = element_blank(),
axis.text.x = element_text(size = 12, hjust = 0.5, color = "black",
vjust = 0, margin = margin(l = 10, r = -50, unit = "pt")),
axis.text.y = element_blank(),
axis.title = element_blank()
)
❝好了今天的介绍到此结束,喜欢的小伙伴欢迎「付费99元」可加入我的「VIP交流群」,即同步获取公众号为期一年推文的代码与PDF文档,同时「也可获取2021年公众号」的文档,(付费文档除外)当然也可以转发此文到朋友圈截图发我,公众号后台会发送给您数据&代码,感谢各位的支持
❞
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流
作者微信
「关注下方公众号下回更新不迷路」添加作者微信请备注单位+方向+姓名
2022-01-25
2022-01-24
2022-01-18
2022-01-17
2022-01-13
2022-01-14
2022-01-11