跟着Plos Biology学作图:R语言ggplot2分组拟合曲线和95%置信区间

2022-04-08 13:44:25 浏览数 (3)

论文

image.png

今天的推文我们重复一下论文中的Figure1A

image.png

首先是读取数据

代码语言:javascript复制
library(readr)
data.use <- read_csv("use-resistance-seasonality/raw_data/antibiotic_use_data.csv")
head(data.use,n=10)

image.png

对数据进行预处理

代码语言:javascript复制
data.use %>% 
  mutate(year_month = 
           paste(as.character(year), 
                 as.character(str_pad(month, 2, pad = "0")), sep = "-")) %>%
  mutate(x = dense_rank(year_month)) -> f1a_data

这里学到了两个新函数

  • str_pad 可以给字符串补长度,比如
代码语言:javascript复制
str_pad("ABC",5,pad="0","right")

就可以把ABC补充到5个,结尾补充两个0,这个很有用。比如原来的数字是1,2,3,4,5 改成01,02,03,04,05这种形式

  • dense_rank()是做排序的

准备配色 和 添加文本标签的数据

代码语言:javascript复制
labels <- data.frame(drug_class = c("Penicillins", "Macrolides", "Quinolones", "Tetracyclines", "Nitrofurans"),
                   x.pos = c(4, 4, 4, 4, 4),
                   y.pos = c(6.6, 3.3, 2.4, 1.5, 0.7))

colors <- setNames( c("#220050", "#b30059","#0091a8","#359023", "#ffa500"), 
                   c("Macrolides", "Nitrofurans", "Penicillins", "Quinolones", "Tetracyclines") )

作图

代码语言:javascript复制
f1a_data %>%
  ggplot(aes(x=x, y=mean_daily_claims_per_10000ppl, 
             group=drug_class, color=drug_class))  
  geom_point(size = 0.7)  
  geom_smooth(aes(fill=drug_class), 
              span = 0.2, size = 0.7,
              method = "loess",
              level=0.95,
              formula = 'y~x') -> f1a1
print(f1a1)

image.png

下面是细节的美化

代码语言:javascript复制
f1a1 
  geom_text(data = labels, aes(x=x.pos, y=y.pos, label=drug_class), hjust = 0, size = 4.2)  
  ylab("Mean daily claims/10,000 people")  
  scale_color_manual(values = colors)  
  scale_fill_manual(values = colors)  
  scale_x_continuous(breaks = c(1, 13, 25, 37, 49), labels = c("Jan '11", "Jan '12", "Jan '13", "Jan '14", "Jan '15"))  
  theme_minimal()  
  theme(panel.grid.minor = element_blank(),
        legend.position = "none",
        axis.text = element_text(size = 10),
        axis.title.x = element_blank(),
        axis.title.y = element_text(size = 11)) 

image.png

0 人点赞