其他
ggplot2优雅的绘制卡通版棒棒糖图
欢迎关注R语言数据分析指南
❝本节来介绍如何使用「ggplot2」来绘制卡通版棒棒糖图,下面通过一个小栗子来进行展示
❞
安装并加载R包
package.list=c("tidyverse","corrplot","corrr","RColorBrewer","showtext","magrittr")
for (package in package.list) {
if (!require(package,character.only=T, quietly=T)) {
install.packages(package)
library(package, character.only=T)
}
}
导入数据
df <- read_csv("data.csv") %>% select(danceability:tempo) %>% select(-mode,-key)
数据清洗
df %<>% correlate() %>% # 计算相关性
pivot_longer(-term, names_to = "group", values_to = "corr") %>%
filter(term == "danceability" & !is.na(corr)) %>%
mutate(group = str_to_title(group),
budge = case_when(corr > 0 ~ -.075,corr < 0 ~ .075, TRUE ~ 0),
align = case_when(corr > 0 ~ 1,corr < 0 ~ 0, TRUE ~ 0))
绘制棒棒糖图
df %>% ggplot(aes(reorder(group, corr), corr)) +
geom_hline(yintercept = 0, linetype = 2) +
geom_segment(aes(x = reorder(group, corr), xend = reorder(group, corr),
y = 0, yend = corr),linetype = 4, size = 1, color = "grey50") +
geom_point(size = 12, aes(fill = corr), shape = 21) +
geom_text(aes(label = round(corr, digits = 2), # 定义小数点位数
color = ifelse(abs(corr) < .2, "black", "white")),
size = 2, family = "rs") +
geom_text(aes(label = group,
y = budge, hjust = align), family = "rs", color = "black") +
scale_fill_gradient2(low = "#D12424", mid = "white", high = "#f28bd5") + #定义点填充颜色
scale_color_manual(values = c("black", "black")) + # 设置字体颜色
scale_y_continuous(breaks = c(-.45, .55), labels = c("Less Danceable", "More Danceable")) +
theme_minimal() + # 主题设置
theme(legend.position = "none",
text = element_text(family = "rs", color = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.y = element_blank(),
axis.line.x = element_line(arrow = arrow(length = unit(.3, "cm"), ends = "both"),
color = "black")) +
coord_flip() # 图像反转
❝感兴趣的小伙伴欢迎加入我微信,付费99元邀请您加入我的付费交流群,同步获取每篇文档的代码并获得更多优质资料,同时「一整年公众号所有文档的数据及代码」会同步上传,同时还会配套精美的「Markdown文档」方便各位学习,公众号右下角可添加小编微信;转发本文到朋友圈后台截图也可获取数据
❞
欢迎大家扫描下方二维码加入「QQ交流群」
「关注下方公众号下回更新不迷路」,如需要加入微信交流群,请在菜单栏处添加作者微信,备注单位+方向+姓名即可邀您
一文搞定ggplot2图像添加阴影
一文搞定GEO & TCGA数据下载
ggraph包优雅的绘制网络图
跟着PNAS学绘图-ggplot2绘制散点图添加渐变拟合曲线
2021年个人年度小总结