SCI图片复现:扇形图
# 加载所需的包
library(ggplot2)
library(dplyr)
# 构建数据框
disease_proportion <- c(24.2, 21.9, 7.6, 5.2, 4.3, 3.2, 2.6, 2.6, 1.8, 1.8, 24.8)
disease_type <- c("Heart disease", "Cancer","Injuries", "CPD", "Stroke",'Type2 diabetes', "AD","Suicide","IP","Chronic liver disease","Other")
group_type <- rep("male", length(disease_proportion))
data <- data.frame(group_type, disease_type, disease_proportion)
# 构建扇形图数据
data <- data %>%
mutate(proportion = disease_proportion/sum(disease_proportion)) %>% # 计算各个疾病的比例
arrange(desc(disease_type)) %>% # 按疾病名称的降序排序
mutate(position = cumsum(proportion)-0.5*proportion) # 计算每个扇形的中心位置
data$x_end <- ifelse(data$proportion < 0.2, 2, 1.8) # 计算标签指示线的结束位置
# 生成扇形图
plot <- ggplot(data, aes(x = "", y = proportion, fill = disease_type)) + # 使用各个疾病的比例为填充变量
geom_bar(width = 1, stat = "identity", color = "white") + # 绘制堆叠条形图
coord_polar("y", start = 0, clip = "off") + # 将条形图转换为极坐标(扇形图)
geom_segment(aes(x = 1.5, y = position, xend = x_end, yend = position), size =0.5, color = 'black') + # 添加指示线
geom_text(aes(y = position, x = x_end, label = paste(disease_type, scales::percent(proportion))), size = 4, color = "black") + # 添加标签
scale_fill_manual(values = c("#aeae5c", "#FB8072", "#1965B0", "#7BAFDE","#882E72","#B17BA6", "#FF7F00", "#FDB462","#E7298A", "#E78AC3","#33A02C")) + # 定义填充色
labs(x = NULL, y = NULL) + # 移除x和y标签
theme_void() + # 移除所有的非数据组件
theme(legend.position = "none") # 移除图例
# 显示图表
print(plot)
# 保存图表为 PDF
ggsave(plot, filename = "pie_chart.pdf", width = 10, height = 10)
# 保存数据为 CSV
write.csv(data, "data.csv", row.names = FALSE)
如果要使用自己的数据,那么数据应该有一个类似的格式,即一个数据框,至少包含以下三列:
- 群体(Group):分类变量,用于表示个体属于哪一组。
- 疾病(disease):分类变量,表示个体的疾病类别。
- 值(value):数值变量,表示各类疾病的值(可能是频数,比例或其他度量)。
结果图片:
阅读剩余
THE END