[GBD数据库挖掘] 13.ggplot2绘制风险因素图

2023-11-23 14:53:52 浏览数 (2)

加载R包

代码语言:javascript复制
library(tidyverse)

导入数据

代码语言:javascript复制
data <- read_tsv("data.tsv")

数据清洗

代码语言:javascript复制
df <- data %>% group_by(age_group, predicted_risk) %>% 
  mutate(pred_risk_med = median(predicted_risk_value)) %>% 
  ungroup()

数据可视化

代码语言:javascript复制
ggplot(df)  
  geom_bar(aes(sex, 1, fill = predicted_risk_value), position = "fill", 
           stat = "identity", size = 1, color = "grey99")  
  geom_text(aes(sex, 1, label = personId), position = "fill",
            stat = "identity", hjust = 1.2,color = "grey99", size=2.8, 
            alpha = 0.8)  
  coord_flip()  
  scale_y_continuous(position = "right")  
  scale_fill_gradientn(colours = rev(RColorBrewer::brewer.pal(4,"RdBu"))) 
  facet_grid(rows = vars(str_wrap(predicted_risk, 25)), cols = vars(age_group))  
  labs(y = "Age group",fill = "Risk")  
  theme_minimal()  
  theme(
    legend.key.height = unit(0.5, "line"),
    legend.key.width = unit(2, "lines"),
    legend.title = element_text(vjust = 1),
    plot.background = element_rect(fill = "grey99",color = NA),
    axis.title.x = element_text(face = "bold"),
    axis.title.y = element_blank(),
    axis.text.x = element_blank(),
    axis.text.y = element_text(color = c("#407075", "#AF559B"),size = 10),
    panel.grid = element_blank(),
    strip.text.x = element_text(face = "bold",size = 10),
    strip.text.y = element_text(angle = 0, hjust = 0,face = "bold",size = 8),
    panel.margin = unit(0, "lines"),
    plot.margin = margin(10,10,10,10)) 
    guides(fill=guide_colorbar(direction="vertical",reverse=F,
                               barwidth=unit(.5,"cm"),
                               barheight=unit(16,"cm")))

0 人点赞