#读取包
library(tidyverse)
library(dplyr)
#设置工作路径
setwd("D:/论文/GBD/other musculoskeletal disorders/分析数据")
#读取数据
data1 <- read.csv("data1.csv")
data2 <- read.csv("data2.csv")
#合并数据并查重
combined_data <- rbind(data1, data2)
# 检查是否有重复行
has_duplicate_rows <- any(duplicated(combined_data))
if (has_duplicate_rows) {
  print("数据框中存在重复行。")
} else {
  print("数据框中不存在重复行。")
}
#unique_data <- unique(combined_data)#若存在重复
#检查数据
str(combined_data)
unique(combined_data$measure)
unique(combined_data$location)
unique(combined_data$age)
#筛选数据
data3 <- combined_data |>
  filter(measure%in%c("Prevalence","YLDs (Years Lived with Disability)")) |>
  filter(metric%in%c("Number","Rate"))
#绘制G20国家和全球不同性别人群其他肌肉骨骼疾病年龄标准化YLDs率和Prevalence率随时间变化趋势
#1、筛选数据
F1 <- data3 |> #filter(location%in%c("Argentina", "Australia", "Brazil", "Canada", "China", "France", 
                                #  "Germany", "India", "Indonesia", "Italy", "Japan", "Republic of Korea", 
                                 # "Mexico", "Russian Federation", "Saudi Arabia", "South Africa", 
                                 # "Turkey", "United Kingdom", "United States of America", "European Union","Global"))|>
filter(age=="Age-standardized")|>
  filter(metric=="Rate")


#绘制Both
F1.1 <- F1 |>
  filter(sex=="Both")|>
  mutate(measure=factor(measure,
                        levels = c("Prevalence","YLDs (Years Lived with Disability)")))
# 假设地名是 location 列中的唯一值
unique_locations <- unique(F1.1$location)

# 为每个地名分配形状编号
shape_mapping <- setNames(1:27, unique_locations)  # 从 15 到 35 的形状编号
# 绘图代码
p1 <- ggplot(F1.1, aes(x = year, y = val, fill = location, color = location, shape = location)) +
  geom_line(size = 1) +
  geom_point(size = 2) +
  facet_wrap(vars(measure), nrow = 2, ncol = 1,
             scales = "free_y",  # 控制 y 轴尺度
             strip.position = "top", labeller = as_labeller(c(
               "Prevalence" = "Both-ASPR per 100,000",
               "YLDs (Years Lived with Disability)" = "Both-ASYR per 100,000"
             ))) +  # 控制标签位置
  labs(x = "", y = "") + 
  theme(strip.text = element_text(size = 14)) +  # 子图标签细节控制
  scale_x_continuous(breaks = seq(min(F1.1$year), max(F1.1$year), by = 5)) +  # 设置X轴5年一间隔
  scale_shape_manual(values = shape_mapping)  # 手动设置形状

p1
ggsave("Both_G20随时间变化趋势1.tiff",p1,height = 12,width = 9,dpi = 600)
#数据处理
F1.1 <- F1.1|>
  arrange(measure,location,year)


#绘制Male
F1.2 <- F1 |>
  filter(sex=="Male")|>
  mutate(measure=factor(measure,
                        levels = c("Prevalence","YLDs (Years Lived with Disability)")))
# 假设地名是 location 列中的唯一值
unique_locations <- unique(F1.2$location)

# 为每个地名分配形状编号
shape_mapping <- setNames(1:27, unique_locations)  # 从 15 到 35 的形状编号
# 绘图代码
p1.1 <- ggplot(F1.2, aes(x = year, y = val, fill = location, color = location, shape = location)) +
  geom_line(size = 1) +
  geom_point(size = 2) +
  facet_wrap(vars(measure), nrow = 2, ncol = 1,
             scales = "free_y",  # 控制 y 轴尺度
             strip.position = "top", labeller = as_labeller(c(
               "Prevalence" = "Male-ASPR per 100,000",
               "YLDs (Years Lived with Disability)" = "Male-ASYR per 100,000"
             ))) +  # 控制标签位置
  labs(x = "", y = "") + 
  theme(strip.text = element_text(size = 14)) +  # 子图标签细节控制
  scale_x_continuous(breaks = seq(min(F1.2$year), max(F1.2$year), by = 5)) +  # 设置X轴5年一间隔
  scale_shape_manual(values = shape_mapping)  # 手动设置形状

p1.1
ggsave("Male_G20随时间变化趋势1.tiff",p1.1,height = 12,width = 9,dpi = 600)
#数据处理
F1.2 <- F1.2|>
  arrange(measure,location,year)


#绘制Female
F1.3 <- F1 |>
  filter(sex=="Female")|>
  mutate(measure=factor(measure,
                        levels = c("Prevalence","YLDs (Years Lived with Disability)")))
# 假设地名是 location 列中的唯一值
unique_locations <- unique(F1.3$location)

# 为每个地名分配形状编号
shape_mapping <- setNames(1:27, unique_locations)  # 从 15 到 35 的形状编号
# 绘图代码
p1.2 <- ggplot(F1.3, aes(x = year, y = val, fill = location, color = location, shape = location)) +
  geom_line(size = 1) +
  geom_point(size = 2) +
  facet_wrap(vars(measure), nrow = 2, ncol = 1,
             scales = "free_y",  # 控制 y 轴尺度
             strip.position = "top", labeller = as_labeller(c(
               "Prevalence" = "Female-ASPR per 100,000",
               "YLDs (Years Lived with Disability)" = "Female-ASYR per 100,000"
             ))) +  # 控制标签位置
  labs(x = "", y = "") + 
  theme(strip.text = element_text(size = 14)) +  # 子图标签细节控制
  scale_x_continuous(breaks = seq(min(F1.3$year), max(F1.3$year), by = 5)) +  # 设置X轴5年一间隔
  scale_shape_manual(values = shape_mapping)  # 手动设置形状

p1.2
ggsave("Female_G20随时间变化趋势1.tiff",p1.2,height = 12,width = 9,dpi = 600)
#数据处理
F1.3 <- F1.3|>
  arrange(measure,location,year)


#合并三个图
#对图片进行合并
library(patchwork)
# 使用patchwork合并图片
p13 <- p1 + theme(legend.position = "none")
p1.13 <-p1.1 + theme(legend.position = "none")
p4 <- (p13 | p1.13 | p1.2) + 
  plot_layout(nrow = 1)  # 设置每行的图片数量
p4
ggsave("全球和G20不同性别人群其他肌肉骨骼疾病随时间变化趋势1.tiff",p4,height = 12,width = 20,dpi = 600)
#分析数据合并、导出
data4<- rbind(F1.1, F1.2,F1.3)
write.csv(data4,"全球和G20不同性别人群其他肌肉骨骼疾病随时间变化趋势分析数据1.csv",row.names = FALSE)

#G20，全球和不同SDI地区1990年和2021年Number、Rate、ASR变化
data5 <- data3 |>
  filter(year%in%c("1990","2021")) |>
  filter(sex=="Both")
#Number
# 定义排序顺序
sort_order <- c("Global", "G20", "High SDI", "High-middle SDI", "Middle SDI", 
                "Low-middle SDI", "Low SDI", "United States of America", 
                "United Kingdom", "Canada", "European Union", "Australia", 
                "Germany", "France", "Italy", "China", "Japan", 
                "Republic of Korea", "India", "Russian Federation", 
                "Indonesia", "Mexico", "Brazil", "Argentina", "Turkey", 
                "Saudi Arabia", "South Africa")

data5.1 <- data5 %>%
  filter(age == "All ages") %>%
  filter(metric == "Number") %>%
  # 将 location 列转换为因子，并指定因子水平为排序顺序
  mutate(location = factor(location, levels = sort_order)) %>%
  arrange(measure, year, location)
#保留三位小数
data5.1_sorted <- data5.1 %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
#格式转化
data5.1_sorted  <- data5.1_sorted  %>%
  mutate(value = paste(val, "(", upper, " to ", lower, ")", sep = ""))
write.csv(data5.1_sorted,"G21990和2021年患病人数变化.csv",row.names = FALSE)
#保留需要的数据
data5.1_sorted1  <- data5.1_sorted  %>% select(1,2,5,6,7,11)


#ASR
# 定义排序顺序
sort_order <- c("Global", "G20", "High SDI", "High-middle SDI", "Middle SDI", 
                "Low-middle SDI", "Low SDI", "United States of America", 
                "United Kingdom", "Canada", "European Union", "Australia", 
                "Germany", "France", "Italy", "China", "Japan", 
                "Republic of Korea", "India", "Russian Federation", 
                "Indonesia", "Mexico", "Brazil", "Argentina", "Turkey", 
                "Saudi Arabia", "South Africa")

data5.2 <- data5 %>%
  filter(age == "Age-standardized") %>%
  filter(metric == "Rate") %>%
  # 将 location 列转换为因子，并指定因子水平为排序顺序
  mutate(location = factor(location, levels = sort_order)) %>%
  arrange(measure, year, location)
#保留三位小数
data5.2_sorted <- data5.2 %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
#格式转化
data5.2_sorted  <- data5.2_sorted  %>%
  mutate(value = paste(val, "(", upper, " to ", lower, ")", sep = ""))
write.csv(data5.2_sorted,"G21990和2021年ASR变化.csv",row.names = FALSE)
#保留需要的数据
data5.2_sorted1  <- data5.2_sorted  %>% select(1,2,5,6,7,11)
data5.3 <- rbind(data5.1_sorted1, data5.2_sorted1)
write.csv(data5.3,"G201990和2021年患病指标变化.csv",row.names = FALSE)

#EAPC变化
EAPC_27<- data3 %>% 
  filter(age == "Age-standardized") %>%
  filter(metric == "Rate") %>%
  filter(sex == "Both") %>%
  filter(measure=='YLDs (Years Lived with Disability)') %>% .[,c(2,7,8)]

EAPC_cal_27 <- data.frame(location=unique(EAPC_27$location),
                          EAPC=rep(0,times=length(unique(EAPC_27$location))),
                          LCI=rep(0,times=length(unique(EAPC_27$location))),
                          UCI=rep(0,times=length(unique(EAPC_27$location))))

for (i in 1:length(unique(EAPC_27$location))){
  country_cal <- as.character(EAPC_cal_27[i,1])
  a <- subset(EAPC_27, EAPC_27$location==country_cal)
  a$y <- log(a$val)
  mod_simp_reg<-lm(y~year,data=a)
  estimate <- (exp(summary(mod_simp_reg)[["coefficients"]][2,1])-1)*100
  low <- (exp(summary(mod_simp_reg)[["coefficients"]][2,1]-1.96*summary(mod_simp_reg)[["coefficients"]][2,2])-1)*100
  high <- (exp(summary(mod_simp_reg)[["coefficients"]][2,1]+1.96*summary(mod_simp_reg)[["coefficients"]][2,2])-1)*100
  EAPC_cal_27[i,2] <- estimate
  EAPC_cal_27[i,3] <- low
  EAPC_cal_27[i,4] <- high
}
EAPC_cal_27 <- EAPC_cal_27 %>% mutate(EAPC=round(EAPC,3),
                                      LCI=round(LCI,3),
                                      UCI=round(UCI,3))
EAPC_cal_27.1 <- EAPC_cal_27 %>% mutate(EAPC_CI = paste(EAPC, UCI,sep = '\n(')) %>% 
  mutate(EAPC_CI = paste(EAPC_CI, LCI,sep = ' to ')) %>% 
  mutate(EAPC_CI = paste0(EAPC_CI, ')'))
#排序
EAPC_cal_27.1$location <- factor(EAPC_cal_27.1$location, levels = sort_order)
EAPC_cal_27.1 <- EAPC_cal_27.1[order(EAPC_cal_27.1$location), ]

write.csv(EAPC_cal_27.1,"EAPC_YLDs.csv",row.names = FALSE)


#EAPC-Prevlence
EAPC_28<- data3 %>% 
  filter(age == "Age-standardized") %>%
  filter(metric == "Rate") %>%
  filter(sex == "Both") %>%
  filter(measure=='Prevalence') %>% .[,c(2,7,8)]

EAPC_cal_28 <- data.frame(location=unique(EAPC_28$location),
                          EAPC=rep(0,times=length(unique(EAPC_28$location))),
                          LCI=rep(0,times=length(unique(EAPC_28$location))),
                          UCI=rep(0,times=length(unique(EAPC_28$location))))

for (i in 1:length(unique(EAPC_28$location))){
  country_cal <- as.character(EAPC_cal_28[i,1])
  a <- subset(EAPC_28, EAPC_28$location==country_cal)
  a$y <- log(a$val)
  mod_simp_reg<-lm(y~year,data=a)
  estimate <- (exp(summary(mod_simp_reg)[["coefficients"]][2,1])-1)*100
  low <- (exp(summary(mod_simp_reg)[["coefficients"]][2,1]-1.96*summary(mod_simp_reg)[["coefficients"]][2,2])-1)*100
  high <- (exp(summary(mod_simp_reg)[["coefficients"]][2,1]+1.96*summary(mod_simp_reg)[["coefficients"]][2,2])-1)*100
  EAPC_cal_28[i,2] <- estimate
  EAPC_cal_28[i,3] <- low
  EAPC_cal_28[i,4] <- high
}
EAPC_cal_28 <- EAPC_cal_28 %>% mutate(EAPC=round(EAPC,3),
                                      LCI=round(LCI,3),
                                      UCI=round(UCI,3))
EAPC_cal_28.1 <- EAPC_cal_28 %>% mutate(EAPC_CI = paste(EAPC, UCI,sep = '\n(')) %>% 
  mutate(EAPC_CI = paste(EAPC_CI, LCI,sep = ' to ')) %>% 
  mutate(EAPC_CI = paste0(EAPC_CI, ')'))
#排序
EAPC_cal_28.1$location <- factor(EAPC_cal_28.1$location, levels = sort_order)
EAPC_cal_28.1 <- EAPC_cal_28.1[order(EAPC_cal_28.1$location), ]

write.csv(EAPC_cal_28.1,"EAPC_Prevalence.csv",row.names = FALSE)


#图2绘制
#作用:描述男性和女性发病人数和率随时间的变化趋势
#Prevalence
F2 <- data3 %>%
  filter(location == "China") %>%
  filter(measure == "Prevalence") %>%
  filter(age=="All ages") %>%
  filter(metric %in% c("Number", "Rate"))
unique(F2$year)  
# 首先，我们需要将数据框转换为长格式，以便于使用ggplot2绘图
F2_long <- F2 %>%
  pivot_longer(cols = starts_with("val"), names_to = "type", values_to = "value") %>%
  mutate(year = factor(year, levels = c("1990", "1991", "1992", "1993", "1994",
                                      "1995", "1996", "1997", "1998", "1999",
                                      "2000", "2001", "2002", "2003", "2004",
                                      "2005", "2006", "2007", "2008", "2009","2010", "2011", "2012", "2013", "2014","2015", "2016","2017", "2018", "2019", "2020", "2021")),
         sex = factor(sex, levels = c("Male", "Female","Both")))
str(F2_long)# 确保是数值型
F2_long$value <- as.numeric(as.character(F2_long$value))
F2_long$upper <- as.numeric(as.character(F2_long$upper))
F2_long$lower <- as.numeric(as.character(F2_long$lower))
# 计算number和rate的最大值，用于缩放
max_number <- max(F2_long$value[F2_long$metric == "Number" & F2_long$sex != "Both"], na.rm = TRUE)
max_rate <- max(F2_long$value[F2_long$metric == "Rate" & F2_long$sex != "Both"], na.rm = TRUE)
# 绘制双y轴复合柱状折线图
# 绘制双y轴复合柱状折线图
# 使用ggsci颜色方案

library(ggplot2)
library(ggsci)

# 确保 year 列是数值类型
F2_long$year <- as.numeric(as.character(F2_long$year))

p2 <- ggplot(F2_long, aes(x = year, color = sex, fill = sex)) +
  geom_bar(data = subset(F2_long, metric == "Number" & sex != "Both"), aes(y = value), stat = "identity", position = position_dodge(0.8), color = "black") +
  geom_smooth(data = subset(F2_long, metric == "Rate" & sex != "Both"), aes(y = value / max_rate * max_number, group = sex, color = sex), method = "loess", se = TRUE, size = 1) +
  geom_errorbar(data = subset(F2_long, metric == "Number" & sex != "Both"), aes(y = value, ymin = lower, ymax = upper), width = 0.2, position = position_dodge(0.8), color = "black") +
  scale_y_continuous(name = "Prevalence (count)", sec.axis = sec_axis(~ . / max_number * max_rate, name = "Prevalence rate (per 100,000)")) +
  # 设置 x 轴的间隔为 5 年
  scale_x_continuous(breaks = seq(min(F2_long$year), max(F2_long$year), by = 5)) +
  scale_fill_npg() +  # 使用 NEJM 颜色方案
  scale_color_npg() +  # 使用 NEJM 颜色方案设置线条颜色
  labs(title = "",
       x = "",
       y = "",
       color = "sex",
       fill = "sex") +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, size = 12),  # 调整 X 轴文本的字体大小
        axis.text.y = element_text(size = 12),  # 调整 Y 轴文本的字体大小
        axis.title.x = element_text(size = 14),  # 调整 X 轴标题的字体大小
        axis.title.y = element_text(size = 14),  # 调整 Y 轴标题的字体大小
        axis.title.y.right = element_text(size = 14),  # 调整第二个 Y 轴标题的字体大小
        legend.text = element_text(size = 12),  # 调整图例文本的字体大小
        legend.title = element_text(size = 14),  # 调整图例标题的字体大小
        plot.title = element_text(size = 18),  # 调整图表标题的字体大小
        plot.subtitle = element_text(size = 16),  # 调整图表副标题的字体大小
        plot.caption = element_text(size = 12),  # 调整图表注释的字体大小
        legend.position = "top",
        legend.justification = "top")

# 显示图表
print(p2)

#保存图片
ggsave("不同性别人群Prevalence随时间变化趋势.tiff", width = 8, height = 6, dpi = 600)
#write.csv(data_long,"Prevalence Count and Rate of Other Musculoskeletal Disorders by Age and Sex in China, 2021.csv",row.names = F)
#写出数据
F2_long <- F2_long %>%
  arrange(sex, metric,age)
#保留三位小数
F2_long_sorted <- F2_long %>%
  mutate(value = round(value, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
#格式转化
F2_long_sorted  <- F2_long_sorted  %>%
  mutate(value = paste(value, "(", upper, " to ", lower, ")", sep = ""))
write.csv(F2_long_sorted,"不同性别随时间Prevalence趋势.csv",row.names = FALSE)

#YLDS
F2.1 <- data3 %>%
  filter(location == "China") %>%
  filter(measure == "YLDs (Years Lived with Disability)") %>%
  filter(age=="All ages") %>%
  filter(metric %in% c("Number", "Rate"))
unique(F2.1$year)  
# 首先，我们需要将数据框转换为长格式，以便于使用ggplot2绘图
F2.1_long <- F2.1 %>%
  pivot_longer(cols = starts_with("val"), names_to = "type", values_to = "value") %>%
  mutate(year = factor(year, levels = c("1990", "1991", "1992", "1993", "1994",
                                        "1995", "1996", "1997", "1998", "1999",
                                        "2000", "2001", "2002", "2003", "2004",
                                        "2005", "2006", "2007", "2008", "2009","2010", "2011", "2012", "2013", "2014","2015", "2016","2017", "2018", "2019", "2020", "2021")),
         sex = factor(sex, levels = c("Male", "Female","Both")))
str(F2.1_long)# 确保是数值型
F2.1_long$value <- as.numeric(as.character(F2.1_long$value))
F2.1_long$upper <- as.numeric(as.character(F2.1_long$upper))
F2.1_long$lower <- as.numeric(as.character(F2.1_long$lower))
# 计算number和rate的最大值，用于缩放
max_number <- max(F2.1_long$value[F2.1_long$metric == "Number" & F2.1_long$sex != "Both"], na.rm = TRUE)
max_rate <- max(F2.1_long$value[F2.1_long$metric == "Rate" & F2.1_long$sex != "Both"], na.rm = TRUE)
# 绘制双y轴复合柱状折线图
# 绘制双y轴复合柱状折线图
# 使用ggsci颜色方案

# 确保 year 列是数值类型
F2.1_long$year <- as.numeric(as.character(F2.1_long$year))

p2.1 <- ggplot(F2.1_long, aes(x = year, color = sex, fill = sex)) +
  geom_bar(data = subset(F2.1_long, metric == "Number" & sex != "Both"), aes(y = value), stat = "identity", position = position_dodge(0.8), color = "black") +
  geom_smooth(data = subset(F2.1_long, metric == "Rate" & sex != "Both"), aes(y = value / max_rate * max_number, group = sex, color = sex), method = "loess", se = TRUE, size = 1) +
  geom_errorbar(data = subset(F2.1_long, metric == "Number" & sex != "Both"), aes(y = value, ymin = lower, ymax = upper), width = 0.2, position = position_dodge(0.8), color = "black") +
  scale_y_continuous(name = "YLDs (Years Lived with Disability) (count)", sec.axis = sec_axis(~ . / max_number * max_rate, name = "YLDs (Years Lived with Disability) rate (per 100,000)")) +
  # 设置 x 轴的间隔为 5 年
  scale_x_continuous(breaks = seq(min(F2.1_long$year), max(F2.1_long$year), by = 5)) +
  scale_fill_npg() +  # 使用 NEJM 颜色方案
  scale_color_npg() +  # 使用 NEJM 颜色方案设置线条颜色
  labs(title = "",
       x = "",
       y = "",
       color = "sex",
       fill = "sex") +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, size = 12),  # 调整 X 轴文本的字体大小
        axis.text.y = element_text(size = 12),  # 调整 Y 轴文本的字体大小
        axis.title.x = element_text(size = 14),  # 调整 X 轴标题的字体大小
        axis.title.y = element_text(size = 14),  # 调整 Y 轴标题的字体大小
        axis.title.y.right = element_text(size = 14),  # 调整第二个 Y 轴标题的字体大小
        legend.text = element_text(size = 12),  # 调整图例文本的字体大小
        legend.title = element_text(size = 14),  # 调整图例标题的字体大小
        plot.title = element_text(size = 18),  # 调整图表标题的字体大小
        plot.subtitle = element_text(size = 16),  # 调整图表副标题的字体大小
        plot.caption = element_text(size = 12),  # 调整图表注释的字体大小
        legend.position = "top",
        legend.justification = "top")

# 显示图表
print(p2.1)

#保存图片
ggsave("不同性别人群YLDS随时间变化趋势.tiff",p2.1, width = 8, height = 6, dpi = 600)
#write.csv(data_long,"Prevalence Count and Rate of Other Musculoskeletal Disorders by Age and Sex in China, 2021.csv",row.names = F)
#写出数据
F2.1_long <- F2.1_long %>%
  arrange(sex, metric,age)
#保留三位小数
F2.1_long_sorted <- F2.1_long %>%
  mutate(value = round(value, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
#格式转化
F2.1_long_sorted  <- F2.1_long_sorted  %>%
  mutate(value = paste(value, "(", upper, " to ", lower, ")", sep = ""))
write.csv(F2.1_long_sorted,"不同性别随时间YLDS趋势.csv",row.names = FALSE)


#G20国家
#Prevalence
F2.2 <- data3 %>%
  filter(location == "G20") %>%
  filter(measure == "Prevalence") %>%
  filter(age=="All ages") %>%
  filter(metric %in% c("Number", "Rate"))
unique(F2.2$year)  
# 首先，我们需要将数据框转换为长格式，以便于使用ggplot2绘图
F2.2_long <- F2.2 %>%
  pivot_longer(cols = starts_with("val"), names_to = "type", values_to = "value") %>%
  mutate(year = factor(year, levels = c("1990", "1991", "1992", "1993", "1994",
                                        "1995", "1996", "1997", "1998", "1999",
                                        "2000", "2001", "2002", "2003", "2004",
                                        "2005", "2006", "2007", "2008", "2009","2010", "2011", "2012", "2013", "2014","2015", "2016","2017", "2018", "2019", "2020", "2021")),
         sex = factor(sex, levels = c("Male", "Female","Both")))
str(F2.2_long)# 确保是数值型
F2.2_long$value <- as.numeric(as.character(F2.2_long$value))
F2.2_long$upper <- as.numeric(as.character(F2.2_long$upper))
F2.2_long$lower <- as.numeric(as.character(F2.2_long$lower))
# 计算number和rate的最大值，用于缩放
max_number <- max(F2.2_long$value[F2.2_long$metric == "Number" & F2.2_long$sex != "Both"], na.rm = TRUE)
max_rate <- max(F2.2_long$value[F2.2_long$metric == "Rate" & F2.2_long$sex != "Both"], na.rm = TRUE)
# 绘制双y轴复合柱状折线图
# 绘制双y轴复合柱状折线图
# 使用ggsci颜色方案

library(ggplot2)
library(ggsci)

# 确保 year 列是数值类型
F2.2_long$year <- as.numeric(as.character(F2.2_long$year))

p2.2 <- ggplot(F2.2_long, aes(x = year, color = sex, fill = sex)) +
  geom_bar(data = subset(F2.2_long, metric == "Number" & sex != "Both"), aes(y = value), stat = "identity", position = position_dodge(0.8), color = "black") +
  geom_smooth(data = subset(F2.2_long, metric == "Rate" & sex != "Both"), aes(y = value / max_rate * max_number, group = sex, color = sex), method = "loess", se = TRUE, size = 1) +
  geom_errorbar(data = subset(F2.2_long, metric == "Number" & sex != "Both"), aes(y = value, ymin = lower, ymax = upper), width = 0.2, position = position_dodge(0.8), color = "black") +
  scale_y_continuous(name = "Prevalence (count)", sec.axis = sec_axis(~ . / max_number * max_rate, name = "Prevalence rate (per 100,000)")) +
  # 设置 x 轴的间隔为 5 年
  scale_x_continuous(breaks = seq(min(F2.2_long$year), max(F2.2_long$year), by = 5)) +
  scale_fill_npg() +  # 使用 NEJM 颜色方案
  scale_color_npg() +  # 使用 NEJM 颜色方案设置线条颜色
  labs(title = "",
       x = "",
       y = "",
       color = "sex",
       fill = "sex") +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, size = 12),  # 调整 X 轴文本的字体大小
        axis.text.y = element_text(size = 12),  # 调整 Y 轴文本的字体大小
        axis.title.x = element_text(size = 14),  # 调整 X 轴标题的字体大小
        axis.title.y = element_text(size = 14),  # 调整 Y 轴标题的字体大小
        axis.title.y.right = element_text(size = 14),  # 调整第二个 Y 轴标题的字体大小
        legend.text = element_text(size = 12),  # 调整图例文本的字体大小
        legend.title = element_text(size = 14),  # 调整图例标题的字体大小
        plot.title = element_text(size = 18),  # 调整图表标题的字体大小
        plot.subtitle = element_text(size = 16),  # 调整图表副标题的字体大小
        plot.caption = element_text(size = 12),  # 调整图表注释的字体大小
        legend.position = "top",
        legend.justification = "top")

# 显示图表
print(p2.2)

#保存图片
ggsave("G20不同性别人群Prevalence随时间变化趋势.tiff", p2.2,width = 8, height = 6, dpi = 600)
#write.csv(data_long,"Prevalence Count and Rate of Other Musculoskeletal Disorders by Age and Sex in China, 2021.csv",row.names = F)
#写出数据
F2.2_long <- F2.2_long %>%
  arrange(sex, metric,age)
#保留三位小数
F2.2_long_sorted <- F2.2_long %>%
  mutate(value = round(value, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
#格式转化
F2.2_long_sorted  <- F2.2_long_sorted  %>%
  mutate(value = paste(value, "(", upper, " to ", lower, ")", sep = ""))
write.csv(F2.2_long_sorted,"G20不同性别随时间Prevalence趋势.csv",row.names = FALSE)


#YLDS
F2.4 <- data3 %>%
  filter(location == "G20") %>%
  filter(measure == "YLDs (Years Lived with Disability)") %>%
  filter(age == "All ages") %>%
  filter(metric %in% c("Number", "Rate"))
unique(F2.4$year)  
# 首先，我们需要将数据框转换为长格式，以便于使用ggplot2绘图
F2.4_long <- F2.4 %>%
  pivot_longer(cols = starts_with("val"), names_to = "type", values_to = "value") %>%
  mutate(year = factor(year, levels = c("1990", "1991", "1992", "1993", "1994",
                                        "1995", "1996", "1997", "1998", "1999",
                                        "2000", "2001", "2002", "2003", "2004",
                                        "2005", "2006", "2007", "2008", "2009",
                                        "2010", "2011", "2012", "2013", "2014",
                                        "2015", "2016", "2017", "2018", "2019",
                                        "2020", "2021")),
         sex = factor(sex, levels = c("Male", "Female", "Both")))
str(F2.4_long)# 确保是数值型
F2.4_long$value <- as.numeric(as.character(F2.4_long$value))
F2.4_long$upper <- as.numeric(as.character(F2.4_long$upper))
F2.4_long$lower <- as.numeric(as.character(F2.4_long$lower))
# 计算number和rate的最大值，用于缩放
max_number <- max(F2.4_long$value[F2.4_long$metric == "Number" & F2.4_long$sex != "Both"], na.rm = TRUE)
max_rate <- max(F2.4_long$value[F2.4_long$metric == "Rate" & F2.4_long$sex != "Both"], na.rm = TRUE)
# 绘制双y轴复合柱状折线图
# 绘制双y轴复合柱状折线图
# 使用ggsci颜色方案

# 确保 year 列是数值类型
F2.4_long$year <- as.numeric(as.character(F2.4_long$year))

p2.4 <- ggplot(F2.4_long, aes(x = year, color = sex, fill = sex)) +
  geom_bar(data = subset(F2.4_long, metric == "Number" & sex != "Both"), aes(y = value), stat = "identity", position = position_dodge(0.8), color = "black") +
  geom_smooth(data = subset(F2.4_long, metric == "Rate" & sex != "Both"), aes(y = value / max_rate * max_number, group = sex, color = sex), method = "loess", se = TRUE, size = 1) +
  geom_errorbar(data = subset(F2.4_long, metric == "Number" & sex != "Both"), aes(y = value, ymin = lower, ymax = upper), width = 0.2, position = position_dodge(0.8), color = "black") +
  scale_y_continuous(name = "YLDs (Years Lived with Disability) (count)", sec.axis = sec_axis(~ . / max_number * max_rate, name = "YLDs (Years Lived with Disability) rate (per 100,000)")) +
  # 设置 x 轴的间隔为 5 年
  scale_x_continuous(breaks = seq(min(F2.4_long$year), max(F2.4_long$year), by = 5)) +
  scale_fill_npg() +  # 使用 NEJM 颜色方案
  scale_color_npg() +  # 使用 NEJM 颜色方案设置线条颜色
  labs(title = "",
       x = "",
       y = "",
       color = "sex",
       fill = "sex") +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, size = 12),  # 调整 X 轴文本的字体大小
        axis.text.y = element_text(size = 12),  # 调整 Y 轴文本的字体大小
        axis.title.x = element_text(size = 14),  # 调整 X 轴标题的字体大小
        axis.title.y = element_text(size = 14),  # 调整 Y 轴标题的字体大小
        axis.title.y.right = element_text(size = 14),  # 调整第二个 Y 轴标题的字体大小
        legend.text = element_text(size = 12),  # 调整图例文本的字体大小
        legend.title = element_text(size = 14),  # 调整图例标题的字体大小
        plot.title = element_text(size = 18),  # 调整图表标题的字体大小
        plot.subtitle = element_text(size = 16),  # 调整图表副标题的字体大小
        plot.caption = element_text(size = 12),  # 调整图表注释的字体大小
        legend.position = "top",
        legend.justification = "top")

# 显示图表
print(p2.4)

#保存图片
ggsave("G20不同性别人群YLDS随时间变化趋势.tiff", p2.4, width = 8, height = 6, dpi = 600)
#write.csv(data_long,"Prevalence Count and Rate of Other Musculoskeletal Disorders by Age and Sex in China, 2021.csv",row.names = F)
#写出数据
F2.4_long <- F2.4_long %>%
  arrange(sex, metric, age)
#保留三位小数
F2.4_long_sorted <- F2.4_long %>%
  mutate(value = round(value, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
#格式转化
F2.4_long_sorted  <- F2.4_long_sorted  %>%
  mutate(value = paste(value, "(", upper, " to ", lower, ")", sep = ""))
write.csv(F2.4_long_sorted, "G20不同性别随时间YLDS趋势.csv", row.names = FALSE)



#预测模型优化
#预测模型Prevalence
#male
#Prevalence预测
#Male
sf6.4.1_Prevalence_Male_Number <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "All ages") %>%
  filter(metric == "Number") %>%
  filter(measure == "Prevalence") %>%
  filter(sex == "Male") 
#Rate
sf6.4.1_Prevalence_Male_Rate <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "Age-standardized") %>%
  filter(metric == "Rate") %>%
  filter(measure == "Prevalence") %>%
  filter(sex == "Male") 
#查看数据
str(sf6.4.1_Prevalence_Male_Rate)
str(sf6.4.1_Prevalence_Male_Number)
# 转换年份为数值型
sf6.4.1_Prevalence_Male_Rate$year <- as.numeric(sf6.4.1_Prevalence_Male_Rate$year)
sf6.4.1_Prevalence_Male_Number$year <- as.numeric(sf6.4.1_Prevalence_Male_Number$year)
# 检查并处理缺失值
sf6.4.1_Prevalence_Male_Rate <- na.omit(sf6.4.1_Prevalence_Male_Rate)
sf6.4.1_Prevalence_Male_Number <- na.omit(sf6.4.1_Prevalence_Male_Number)
#按时间进行排序
sf6.4.1_Prevalence_Male_Rate <- sf6.4.1_Prevalence_Male_Rate %>%
  arrange(year)
sf6.4.1_Prevalence_Male_Number <- sf6.4.1_Prevalence_Male_Number %>%
  arrange(year)
# 假设年份是连续的，且数据是按年份排序的
ts_sf6.4.1_Prevalence_Male_Rate <- ts(sf6.4.1_Prevalence_Male_Rate$val, start=c(min(sf6.4.1_Prevalence_Male_Rate$year)), frequency=1)
ts_sf6.4.1_Prevalence_Male_Number <- ts(sf6.4.1_Prevalence_Male_Number$val, start=c(min(sf6.4.1_Prevalence_Male_Number$year)), frequency=1)
install.packages("forecast")
library(forecast)
fit_Rate <- auto.arima(ts_sf6.4.1_Prevalence_Male_Rate)
fit_Number <- auto.arima(ts_sf6.4.1_Prevalence_Male_Number)
# 预测未来29年
forecast_result_Rate <- forecast(fit_Rate, h=20) 
forecast_result_Number <- forecast(fit_Number, h=20)
plot(forecast_result_Rate)
plot(forecast_result_Number)
#检验
summary(fit_Rate)
Box.test(fit_Rate$residuals, type = "Ljung-Box")
library(ggplot2)
# 假设forecast_result是你的预测结果对象
# 首先，我们需要从forecast对象中提取预测值和置信区间
forecast_data_Rate <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Rate$mean,
  upper = forecast_result_Rate$upper[, "80%"],
  lower = forecast_result_Rate$lower[, "80%"]
)
forecast_data_Number <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Number$mean,
  upper = forecast_result_Number$upper[, "80%"],
  lower = forecast_result_Number$lower[, "80%"]
)
#保留后四列
Male_Rate <- sf6.4.1_Prevalence_Male_Rate[, tail(names(sf6.4.1_Prevalence_Male_Rate), 4)]
Male_Number <- sf6.4.1_Prevalence_Male_Number[, tail(names(sf6.4.1_Prevalence_Male_Number), 4)]
#合并数据
all_data_Rate <- rbind(Male_Rate, forecast_data_Rate)
all_data_Number <- rbind(Male_Number, forecast_data_Number)
# 绘制图表
library(ggplot2)
library(dplyr)
# 假设all_data是包含所有数据的数据框，并且已经包含了区分Actual和Predicted的列
# 如果没有，你需要先创建这个列
all_data_Rate <- all_data_Rate %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
all_data_Number <- all_data_Number %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
max_number <- max(all_data_Number$val, na.rm = TRUE)
max_rate <- max(all_data_Rate$val, na.rm = TRUE)

# 假设 all_data_Number 和 all_data_Rate 已经定义，max_number 和 max_rate 也已经计算好
library(ggplot2)
library(ggsci) # 如果你使用了 ggsci 中的颜色方案

# 确保 year 是数值类型
all_data_Rate$year <- as.numeric(as.character(all_data_Rate$year))
all_data_Number$year <- as.numeric(as.character(all_data_Number$year))

# 筛选出 2021 年之后的数据
post_2021_data <- subset(all_data_Rate, year > 2021)

# 绘制图形
# 假设 all_data_Number、all_data_Rate、post_2021_data、max_number 和 max_rate 已经定义
library(ggplot2)
library(ggsci) 

# 确保 year 是数值类型
all_data_Rate$year <- as.numeric(as.character(all_data_Rate$year))
all_data_Number$year <- as.numeric(as.character(all_data_Number$year))

sf6.4.1_Prevalence <- ggplot() +
  # 添加柱状图表示预测Prevalence人数
  geom_bar(data = all_data_Number, aes(x = year, y = val, fill = Type), stat = "identity", position = position_dodge(width = 0.8), alpha = 0.5) +
  # 绘制实际值和预测值的线
  geom_line(data = all_data_Rate, aes(x = year, y = val / max_rate * max_number, color = Type), size = 0.8) +
  # 绘制预测数据的点
  geom_point(data = subset(all_data_Rate, Type == "True value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  geom_point(data = subset(all_data_Rate, Type == "Predicted value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  # 为 2021 年后的数据添加置信区间
  geom_ribbon(data = post_2021_data, aes(x = year, ymin = lower / max_rate * max_number, ymax = upper / max_rate * max_number, fill = Type), alpha = 0.2) +
  scale_y_continuous(name = "Prevalence (count)", sec.axis = sec_axis(~. / max_number * max_rate, name = "Age - standardized prevalence rate (per 100,000)")) +
  scale_fill_npg() +  # 使用bmj颜色方案
  scale_color_npg() +  # 使用bmj颜色方案设置线条颜色
  labs(title = "Male",  # 设置标题
       x = " ",  # 设置X轴标签
       y = " ") +  # 设置Y轴标签
  theme_classic() +  # 使用经典主题
  scale_x_continuous(breaks = seq(min(all_data_Rate$year), max(all_data_Rate$year), by = 5)) +
  geom_vline(xintercept = 2021, linetype = "dashed", color = "black") +  # 在2021年的位置添加一条竖直的虚线
  theme(
    legend.position = "top",
    legend.justification = c("left", "top"),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),  # 调整图表标题字体大小
    axis.title.x = element_text(size = 16),  # 调整 X 轴标题字体大小
    axis.title.y = element_text(size = 16),  # 调整 Y 轴标题字体大小
    axis.text.x = element_text(size = 12),  # 调整 X 轴刻度文本字体大小
    axis.text.y = element_text(size = 12),  # 调整 Y 轴刻度文本字体大小
    legend.title = element_text(size = 16),  # 调整图例标题字体大小
    legend.text = element_text(size = 12)  # 调整图例文本字体大小
  )  

# 显示图形
print(sf6.4.1_Prevalence)

ggsave("Prevalence_Male预测.tiff",sf6.4.1_Prevalence,height = 6,width = 8,dpi = 600)
# 下载数据
# 保留小数点后两位
all_data_Number1 <- all_data_Number %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Rate1 <- all_data_Rate %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Number预测 <- all_data_Number1  %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
all_data_Rate预测 <- all_data_Rate1 %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
# 选取前两列
all_data_Number预测 <- all_data_Number预测 %>%
  select_at(1:2)
all_data_Rate预测 <- all_data_Rate预测 %>%
  select_at(1:2)
sf6.4.1_Prevalence_Male预测 <- merge(all_data_Number预测, all_data_Rate预测, by = "year")
# 更改列名
sf6.4.1_Prevalence_Male预测 <- sf6.4.1_Prevalence_Male预测 %>%
  rename(Year = year, Number = val.x, Rate = val.y)
write.csv(sf6.4.1_Prevalence_Male预测,"Prevalence预测数据（Male）.csv", row.names = FALSE)


#Female_prevalence
sf6.4.1_Prevalence_Female_Number <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "All ages") %>%
  filter(metric == "Number") %>%
  filter(measure == "Prevalence") %>%
  filter(sex == "Female") 
#Rate
sf6.4.1_Prevalence_Female_Rate <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "Age-standardized") %>%
  filter(metric == "Rate") %>%
  filter(measure == "Prevalence") %>%
  filter(sex == "Female") 
#查看数据
str(sf6.4.1_Prevalence_Female_Rate)
str(sf6.4.1_Prevalence_Female_Number)
# 转换年份为数值型
sf6.4.1_Prevalence_Female_Rate$year <- as.numeric(sf6.4.1_Prevalence_Female_Rate$year)
sf6.4.1_Prevalence_Female_Number$year <- as.numeric(sf6.4.1_Prevalence_Female_Number$year)
# 检查并处理缺失值
sf6.4.1_Prevalence_Female_Rate <- na.omit(sf6.4.1_Prevalence_Female_Rate)
sf6.4.1_Prevalence_Female_Number <- na.omit(sf6.4.1_Prevalence_Female_Number)
#按时间进行排序
sf6.4.1_Prevalence_Female_Rate <- sf6.4.1_Prevalence_Female_Rate %>%
  arrange(year)
sf6.4.1_Prevalence_Female_Number <- sf6.4.1_Prevalence_Female_Number %>%
  arrange(year)
# 假设年份是连续的，且数据是按年份排序的
ts_sf6.4.1_Prevalence_Female_Rate <- ts(sf6.4.1_Prevalence_Female_Rate$val, start=c(min(sf6.4.1_Prevalence_Female_Rate$year)), frequency=1)
ts_sf6.4.1_Prevalence_Female_Number <- ts(sf6.4.1_Prevalence_Female_Number$val, start=c(min(sf6.4.1_Prevalence_Female_Number$year)), frequency=1)
# install.packages("forecast")  如果已经安装，可注释掉这行
library(forecast)
fit_Rate <- auto.arima(ts_sf6.4.1_Prevalence_Female_Rate)
fit_Number <- auto.arima(ts_sf6.4.1_Prevalence_Female_Number)
# 预测未来29年
forecast_result_Rate <- forecast(fit_Rate, h=20) 
forecast_result_Number <- forecast(fit_Number, h=20)
plot(forecast_result_Rate)
plot(forecast_result_Number)
library(ggplot2)
# 假设forecast_result是你的预测结果对象
# 首先，我们需要从forecast对象中提取预测值和置信区间
forecast_data_Rate <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Rate$mean,
  upper = forecast_result_Rate$upper[, "80%"],
  lower = forecast_result_Rate$lower[, "80%"]
)
forecast_data_Number <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Number$mean,
  upper = forecast_result_Number$upper[, "80%"],
  lower = forecast_result_Number$lower[, "80%"]
)
#保留后四列
Female_Rate <- sf6.4.1_Prevalence_Female_Rate[, tail(names(sf6.4.1_Prevalence_Female_Rate), 4)]
Female_Number <- sf6.4.1_Prevalence_Female_Number[, tail(names(sf6.4.1_Prevalence_Female_Number), 4)]
#合并数据
all_data_Rate <- rbind(Female_Rate, forecast_data_Rate)
all_data_Number <- rbind(Female_Number, forecast_data_Number)
# 绘制图表
library(ggplot2)
library(dplyr)
# 假设all_data是包含所有数据的数据框，并且已经包含了区分Actual和Predicted的列
# 如果没有，你需要先创建这个列
all_data_Rate <- all_data_Rate %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
all_data_Number <- all_data_Number %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
max_number <- max(all_data_Number$val, na.rm = TRUE)
max_rate <- max(all_data_Rate$val, na.rm = TRUE)

# 假设 all_data_Number 和 all_data_Rate 已经定义，max_number 和 max_rate 也已经计算好
library(ggplot2)
library(ggsci) # 如果你使用了 ggsci 中的颜色方案

# 确保 year 是数值类型
all_data_Rate$year <- as.numeric(as.character(all_data_Rate$year))
all_data_Number$year <- as.numeric(as.character(all_data_Number$year))

# 筛选出 2021 年之后的数据
post_2021_data <- subset(all_data_Rate, year > 2021)

# 绘制图形
# 假设 all_data_Number、all_data_Rate、post_2021_data、max_number 和 max_rate 已经定义
library(ggplot2)
library(ggsci) 

sf6.4.1_Prevalence <- ggplot() +
  # 添加柱状图表示预测Prevalence人数
  geom_bar(data = all_data_Number, aes(x = year, y = val, fill = Type), stat = "identity", position = position_dodge(width = 0.8), alpha = 0.5) +
  # 绘制实际值和预测值的线
  geom_line(data = all_data_Rate, aes(x = year, y = val / max_rate * max_number, color = Type), size = 0.8) +
  # 绘制预测数据的点
  geom_point(data = subset(all_data_Rate, Type == "True value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  geom_point(data = subset(all_data_Rate, Type == "Predicted value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  # 为 2021 年后的数据添加置信区间
  geom_ribbon(data = post_2021_data, aes(x = year, ymin = lower / max_rate * max_number, ymax = upper / max_rate * max_number, fill = Type), alpha = 0.2) +
  scale_y_continuous(name = "Prevalence (count)", sec.axis = sec_axis(~. / max_number * max_rate, name = "Age - standardized prevalence rate (per 100,000)")) +
  scale_fill_npg() +  # 使用bmj颜色方案
  scale_color_npg() +  # 使用bmj颜色方案设置线条颜色
  labs(title = "Female",  # 设置标题
       x = " ",  # 设置X轴标签
       y = " ") +  # 设置Y轴标签
  theme_classic() +  # 使用经典主题
  scale_x_continuous(breaks = seq(min(all_data_Rate$year), max(all_data_Rate$year), by = 5)) +
  geom_vline(xintercept = 2021, linetype = "dashed", color = "black") +  # 在2021年的位置添加一条竖直的虚线
  theme(
    legend.position = "top",
    legend.justification = c("left", "top"),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),  # 调整图表标题字体大小
    axis.title.x = element_text(size = 16),  # 调整 X 轴标题字体大小
    axis.title.y = element_text(size = 16),  # 调整 Y 轴标题字体大小
    axis.text.x = element_text(size = 12),  # 调整 X 轴刻度文本字体大小
    axis.text.y = element_text(size = 12),  # 调整 Y 轴刻度文本字体大小
    legend.title = element_text(size = 16),  # 调整图例标题字体大小
    legend.text = element_text(size = 12)  # 调整图例文本字体大小
  )  

# 显示图形
print(sf6.4.1_Prevalence)

ggsave("Prevalence_Female预测.tiff",sf6.4.1_Prevalence,height = 6,width = 8,dpi = 600)
# 下载数据
# 保留小数点后两位
all_data_Number1 <- all_data_Number %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Rate1 <- all_data_Rate %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Number预测 <- all_data_Number1  %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
all_data_Rate预测 <- all_data_Rate1 %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
# 选取前两列
all_data_Number预测 <- all_data_Number预测 %>%
  select_at(1:2)
all_data_Rate预测 <- all_data_Rate预测 %>%
  select_at(1:2)
sf6.4.1_Prevalence_Female预测 <- merge(all_data_Number预测, all_data_Rate预测, by = "year")
# 更改列名
sf6.4.1_Prevalence_Female预测 <- sf6.4.1_Prevalence_Female预测 %>%
  rename(Year = year, Number = val.x, Rate = val.y)
write.csv(sf6.4.1_Prevalence_Female预测,"Prevalence预测数据（Female）.csv", row.names = FALSE)


#BOth
sf6.4.1_Prevalence_Both_Number <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "All ages") %>%
  filter(metric == "Number") %>%
  filter(measure == "Prevalence") %>%
  filter(sex == "Both") 
#Rate
sf6.4.1_Prevalence_Both_Rate <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "Age-standardized") %>%
  filter(metric == "Rate") %>%
  filter(measure == "Prevalence") %>%
  filter(sex == "Both") 
#查看数据
str(sf6.4.1_Prevalence_Both_Rate)
str(sf6.4.1_Prevalence_Both_Number)
# 转换年份为数值型
sf6.4.1_Prevalence_Both_Rate$year <- as.numeric(sf6.4.1_Prevalence_Both_Rate$year)
sf6.4.1_Prevalence_Both_Number$year <- as.numeric(sf6.4.1_Prevalence_Both_Number$year)
# 检查并处理缺失值
sf6.4.1_Prevalence_Both_Rate <- na.omit(sf6.4.1_Prevalence_Both_Rate)
sf6.4.1_Prevalence_Both_Number <- na.omit(sf6.4.1_Prevalence_Both_Number)
#按时间进行排序
sf6.4.1_Prevalence_Both_Rate <- sf6.4.1_Prevalence_Both_Rate %>%
  arrange(year)
sf6.4.1_Prevalence_Both_Number <- sf6.4.1_Prevalence_Both_Number %>%
  arrange(year)
# 假设年份是连续的，且数据是按年份排序的
ts_sf6.4.1_Prevalence_Both_Rate <- ts(sf6.4.1_Prevalence_Both_Rate$val, start=c(min(sf6.4.1_Prevalence_Both_Rate$year)), frequency=1)
ts_sf6.4.1_Prevalence_Both_Number <- ts(sf6.4.1_Prevalence_Both_Number$val, start=c(min(sf6.4.1_Prevalence_Both_Number$year)), frequency=1)
# install.packages("forecast")  如果已经安装，可注释掉这行
library(forecast)
fit_Rate <- auto.arima(ts_sf6.4.1_Prevalence_Both_Rate)
fit_Number <- auto.arima(ts_sf6.4.1_Prevalence_Both_Number)
# 预测未来29年
forecast_result_Rate <- forecast(fit_Rate, h=20) 
forecast_result_Number <- forecast(fit_Number, h=20)
plot(forecast_result_Rate)
plot(forecast_result_Number)
library(ggplot2)
# 假设forecast_result是你的预测结果对象
# 首先，我们需要从forecast对象中提取预测值和置信区间
forecast_data_Rate <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Rate$mean,
  upper = forecast_result_Rate$upper[, "80%"],
  lower = forecast_result_Rate$lower[, "80%"]
)
forecast_data_Number <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Number$mean,
  upper = forecast_result_Number$upper[, "80%"],
  lower = forecast_result_Number$lower[, "80%"]
)
#保留后四列
Both_Rate <- sf6.4.1_Prevalence_Both_Rate[, tail(names(sf6.4.1_Prevalence_Both_Rate), 4)]
Both_Number <- sf6.4.1_Prevalence_Both_Number[, tail(names(sf6.4.1_Prevalence_Both_Number), 4)]
#合并数据
all_data_Rate <- rbind(Both_Rate, forecast_data_Rate)
all_data_Number <- rbind(Both_Number, forecast_data_Number)
# 绘制图表
library(ggplot2)
library(dplyr)
# 假设all_data是包含所有数据的数据框，并且已经包含了区分Actual和Predicted的列
# 如果没有，你需要先创建这个列
all_data_Rate <- all_data_Rate %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
all_data_Number <- all_data_Number %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
max_number <- max(all_data_Number$val, na.rm = TRUE)
max_rate <- max(all_data_Rate$val, na.rm = TRUE)

# 假设 all_data_Number 和 all_data_Rate 已经定义，max_number 和 max_rate 也已经计算好
library(ggplot2)
library(ggsci) # 如果你使用了 ggsci 中的颜色方案

# 确保 year 是数值类型
all_data_Rate$year <- as.numeric(as.character(all_data_Rate$year))
all_data_Number$year <- as.numeric(as.character(all_data_Number$year))

# 筛选出 2021 年之后的数据
post_2021_data <- subset(all_data_Rate, year > 2021)

sf6.4.1_Prevalence <- ggplot() +
  # 添加柱状图表示预测Prevalence人数
  geom_bar(data = all_data_Number, aes(x = year, y = val, fill = Type), stat = "identity", position = position_dodge(width = 0.8), alpha = 0.5) +
  # 绘制实际值和预测值的线
  geom_line(data = all_data_Rate, aes(x = year, y = val / max_rate * max_number, color = Type), size = 0.8) +
  # 绘制预测数据的点
  geom_point(data = subset(all_data_Rate, Type == "True value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  geom_point(data = subset(all_data_Rate, Type == "Predicted value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  # 为 2021 年后的数据添加置信区间
  geom_ribbon(data = post_2021_data, aes(x = year, ymin = lower / max_rate * max_number, ymax = upper / max_rate * max_number, fill = Type), alpha = 0.2) +
  scale_y_continuous(name = "Prevalence (count)", sec.axis = sec_axis(~. / max_number * max_rate, name = "Age - standardized prevalence rate (per 100,000)")) +
  scale_fill_npg() +  # 使用bmj颜色方案
  scale_color_npg() +  # 使用bmj颜色方案设置线条颜色
  labs(title = "Both",  # 设置标题
       x = " ",  # 设置X轴标签
       y = " ") +  # 设置Y轴标签
  theme_classic() +  # 使用经典主题
  scale_x_continuous(breaks = seq(min(all_data_Rate$year), max(all_data_Rate$year), by = 5)) +
  geom_vline(xintercept = 2021, linetype = "dashed", color = "black") +  # 在2021年的位置添加一条竖直的虚线
  theme(
    legend.position = "top",
    legend.justification = c("left", "top"),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),  # 调整图表标题字体大小
    axis.title.x = element_text(size = 16),  # 调整 X 轴标题字体大小
    axis.title.y = element_text(size = 16),  # 调整 Y 轴标题字体大小
    axis.text.x = element_text(size = 12),  # 调整 X 轴刻度文本字体大小
    axis.text.y = element_text(size = 12),  # 调整 Y 轴刻度文本字体大小
    legend.title = element_text(size = 16),  # 调整图例标题字体大小
    legend.text = element_text(size = 12)  # 调整图例文本字体大小
  )  

# 显示图形
print(sf6.4.1_Prevalence)

ggsave("Prevalence_Both预测.tiff",sf6.4.1_Prevalence,height = 6,width = 8,dpi = 600)
# 下载数据
# 保留小数点后两位
all_data_Number1 <- all_data_Number %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Rate1 <- all_data_Rate %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Number预测 <- all_data_Number1  %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
all_data_Rate预测 <- all_data_Rate1 %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
# 选取前两列
all_data_Number预测 <- all_data_Number预测 %>%
  select_at(1:2)
all_data_Rate预测 <- all_data_Rate预测 %>%
  select_at(1:2)
sf6.4.1_Prevalence_Both预测 <- merge(all_data_Number预测, all_data_Rate预测, by = "year")
# 更改列名
sf6.4.1_Prevalence_Both预测 <- sf6.4.1_Prevalence_Both预测 %>%
  rename(Year = year, Number = val.x, Rate = val.y)
write.csv(sf6.4.1_Prevalence_Both预测,"Prevalence预测数据（Both）.csv", row.names = FALSE)



#YLDS预测
#Male
#YLDs (Years Lived with Disability)预测
#Male
#YLDs预测
#Male
sf6.5_YLDs_Male_Number <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "All ages") %>%
  filter(metric == "Number") %>%
  filter(measure == "YLDs (Years Lived with Disability)") %>%
  filter(sex == "Male") 
#Rate
sf6.5_YLDs_Male_Rate <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "Age-standardized") %>%
  filter(metric == "Rate") %>%
  filter(measure == "YLDs (Years Lived with Disability)") %>%
  filter(sex == "Male") 
#查看数据
str(sf6.5_YLDs_Male_Rate)
str(sf6.5_YLDs_Male_Number)
# 转换年份为数值型
sf6.5_YLDs_Male_Rate$year <- as.numeric(sf6.5_YLDs_Male_Rate$year)
sf6.5_YLDs_Male_Number$year <- as.numeric(sf6.5_YLDs_Male_Number$year)
# 检查并处理缺失值
sf6.5_YLDs_Male_Rate <- na.omit(sf6.5_YLDs_Male_Rate)
sf6.5_YLDs_Male_Number <- na.omit(sf6.5_YLDs_Male_Number)
#按时间进行排序
sf6.5_YLDs_Male_Rate <- sf6.5_YLDs_Male_Rate %>%
  arrange(year)
sf6.5_YLDs_Male_Number <- sf6.5_YLDs_Male_Number %>%
  arrange(year)
# 假设年份是连续的，且数据是按年份排序的
ts_sf6.5_YLDs_Male_Rate <- ts(sf6.5_YLDs_Male_Rate$val, start=c(min(sf6.5_YLDs_Male_Rate$year)), frequency=1)
ts_sf6.5_YLDs_Male_Number <- ts(sf6.5_YLDs_Male_Number$val, start=c(min(sf6.5_YLDs_Male_Number$year)), frequency=1)
# install.packages("forecast")  如果已经安装，可注释掉这行
library(forecast)
fit_Rate <- auto.arima(ts_sf6.5_YLDs_Male_Rate)
fit_Number <- auto.arima(ts_sf6.5_YLDs_Male_Number)
# 预测未来29年
forecast_result_Rate <- forecast(fit_Rate, h=20) 
forecast_result_Number <- forecast(fit_Number, h=20)
plot(forecast_result_Rate)
plot(forecast_result_Number)
library(ggplot2)
# 假设forecast_result是你的预测结果对象
# 首先，我们需要从forecast对象中提取预测值和置信区间
forecast_data_Rate <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Rate$mean,
  upper = forecast_result_Rate$upper[, "80%"],
  lower = forecast_result_Rate$lower[, "80%"]
)
forecast_data_Number <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Number$mean,
  upper = forecast_result_Number$upper[, "80%"],
  lower = forecast_result_Number$lower[, "80%"]
)
#保留后四列
Male_Rate <- sf6.5_YLDs_Male_Rate[, tail(names(sf6.5_YLDs_Male_Rate), 4)]
Male_Number <- sf6.5_YLDs_Male_Number[, tail(names(sf6.5_YLDs_Male_Number), 4)]
#合并数据
all_data_Rate <- rbind(Male_Rate, forecast_data_Rate)
all_data_Number <- rbind(Male_Number, forecast_data_Number)
# 绘制图表
library(ggplot2)
library(dplyr)
# 假设all_data是包含所有数据的数据框，并且已经包含了区分Actual和Predicted的列
# 如果没有，你需要先创建这个列
all_data_Rate <- all_data_Rate %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
all_data_Number <- all_data_Number %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
max_number <- max(all_data_Number$val, na.rm = TRUE)
max_rate <- max(all_data_Rate$val, na.rm = TRUE)

# 假设 all_data_Number 和 all_data_Rate 已经定义，max_number 和 max_rate 也已经计算好
library(ggplot2)
library(ggsci) # 如果你使用了 ggsci 中的颜色方案

# 确保 year 是数值类型
all_data_Rate$year <- as.numeric(as.character(all_data_Rate$year))
all_data_Number$year <- as.numeric(as.character(all_data_Number$year))

# 筛选出 2021 年之后的数据
post_2021_data <- subset(all_data_Rate, year > 2021)


sf6.5_YLDs <- ggplot() +
  # 添加柱状图表示预测YLDs人数
  geom_bar(data = all_data_Number, aes(x = year, y = val, fill = Type), stat = "identity", position = position_dodge(width = 0.8), alpha = 0.5) +
  # 绘制实际值和预测值的线
  geom_line(data = all_data_Rate, aes(x = year, y = val / max_rate * max_number, color = Type), size = 0.8) +
  # 绘制预测数据的点
  geom_point(data = subset(all_data_Rate, Type == "True value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  geom_point(data = subset(all_data_Rate, Type == "Predicted value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  # 为 2021 年后的数据添加置信区间
  geom_ribbon(data = post_2021_data, aes(x = year, ymin = lower / max_rate * max_number, ymax = upper / max_rate * max_number, fill = Type), alpha = 0.2) +
  scale_y_continuous(name = "YLDs (count)", sec.axis = sec_axis(~. / max_number * max_rate, name = "Age - standardized YLDs rate (per 100,000)")) +
  scale_fill_npg() +  # 使用bmj颜色方案
  scale_color_npg() +  # 使用bmj颜色方案设置线条颜色
  labs(title = "Male",  # 设置标题
       x = " ",  # 设置X轴标签
       y = " ") +  # 设置Y轴标签
  theme_classic() +  # 使用经典主题
  scale_x_continuous(breaks = seq(min(all_data_Rate$year), max(all_data_Rate$year), by = 5)) +
  geom_vline(xintercept = 2021, linetype = "dashed", color = "black") +  # 在2021年的位置添加一条竖直的虚线
  theme(
    legend.position = "top",
    legend.justification = c("left", "top"),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),  # 调整图表标题字体大小
    axis.title.x = element_text(size = 16),  # 调整 X 轴标题字体大小
    axis.title.y = element_text(size = 16),  # 调整 Y 轴标题字体大小
    axis.text.x = element_text(size = 12),  # 调整 X 轴刻度文本字体大小
    axis.text.y = element_text(size = 12),  # 调整 Y 轴刻度文本字体大小
    legend.title = element_text(size = 16),  # 调整图例标题字体大小
    legend.text = element_text(size = 12)  # 调整图例文本字体大小
  )  

# 显示图形
print(sf6.5_YLDs)

ggsave("YLDs_Male预测.tiff",sf6.5_YLDs,height = 6,width = 8,dpi = 600)
# 下载数据
# 保留小数点后两位
all_data_Number1 <- all_data_Number %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Rate1 <- all_data_Rate %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Number预测 <- all_data_Number1  %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
all_data_Rate预测 <- all_data_Rate1 %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
# 选取前两列
all_data_Number预测 <- all_data_Number预测 %>%
  select_at(1:2)
all_data_Rate预测 <- all_data_Rate预测 %>%
  select_at(1:2)
sf6.5_YLDs_Male预测 <- merge(all_data_Number预测, all_data_Rate预测, by = "year")
# 更改列名
sf6.5_YLDs_Male预测 <- sf6.5_YLDs_Male预测 %>%
  rename(Year = year, Number = val.x, Rate = val.y)
write.csv(sf6.5_YLDs_Male预测,"YLDs预测数据（Male）.csv", row.names = FALSE)


#Female
#YLDs预测
#Female
sf6.5_YLDs_Female_Number <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "All ages") %>%
  filter(metric == "Number") %>%
  filter(measure == "YLDs (Years Lived with Disability)") %>%
  filter(sex == "Female") 
#Rate
sf6.5_YLDs_Female_Rate <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "Age-standardized") %>%
  filter(metric == "Rate") %>%
  filter(measure == "YLDs (Years Lived with Disability)") %>%
  filter(sex == "Female") 
#查看数据
str(sf6.5_YLDs_Female_Rate)
str(sf6.5_YLDs_Female_Number)
# 转换年份为数值型
sf6.5_YLDs_Female_Rate$year <- as.numeric(sf6.5_YLDs_Female_Rate$year)
sf6.5_YLDs_Female_Number$year <- as.numeric(sf6.5_YLDs_Female_Number$year)
# 检查并处理缺失值
sf6.5_YLDs_Female_Rate <- na.omit(sf6.5_YLDs_Female_Rate)
sf6.5_YLDs_Female_Number <- na.omit(sf6.5_YLDs_Female_Number)
#按时间进行排序
sf6.5_YLDs_Female_Rate <- sf6.5_YLDs_Female_Rate %>%
  arrange(year)
sf6.5_YLDs_Female_Number <- sf6.5_YLDs_Female_Number %>%
  arrange(year)
# 假设年份是连续的，且数据是按年份排序的
ts_sf6.5_YLDs_Female_Rate <- ts(sf6.5_YLDs_Female_Rate$val, start=c(min(sf6.5_YLDs_Female_Rate$year)), frequency=1)
ts_sf6.5_YLDs_Female_Number <- ts(sf6.5_YLDs_Female_Number$val, start=c(min(sf6.5_YLDs_Female_Number$year)), frequency=1)
# install.packages("forecast")  如果已经安装，可注释掉这行
library(forecast)
fit_Rate <- auto.arima(ts_sf6.5_YLDs_Female_Rate)
fit_Number <- auto.arima(ts_sf6.5_YLDs_Female_Number)
# 预测未来29年
forecast_result_Rate <- forecast(fit_Rate, h=20) 
forecast_result_Number <- forecast(fit_Number, h=20)
plot(forecast_result_Rate)
plot(forecast_result_Number)
library(ggplot2)
# 假设forecast_result是你的预测结果对象
# 首先，我们需要从forecast对象中提取预测值和置信区间
forecast_data_Rate <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Rate$mean,
  upper = forecast_result_Rate$upper[, "80%"],
  lower = forecast_result_Rate$lower[, "80%"]
)
forecast_data_Number <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Number$mean,
  upper = forecast_result_Number$upper[, "80%"],
  lower = forecast_result_Number$lower[, "80%"]
)
#保留后四列
Female_Rate <- sf6.5_YLDs_Female_Rate[, tail(names(sf6.5_YLDs_Female_Rate), 4)]
Female_Number <- sf6.5_YLDs_Female_Number[, tail(names(sf6.5_YLDs_Female_Number), 4)]
#合并数据
all_data_Rate <- rbind(Female_Rate, forecast_data_Rate)
all_data_Number <- rbind(Female_Number, forecast_data_Number)
# 绘制图表
library(ggplot2)
library(dplyr)
# 假设all_data是包含所有数据的数据框，并且已经包含了区分Actual和Predicted的列
# 如果没有，你需要先创建这个列
all_data_Rate <- all_data_Rate %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
all_data_Number <- all_data_Number %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
max_number <- max(all_data_Number$val, na.rm = TRUE)
max_rate <- max(all_data_Rate$val, na.rm = TRUE)

# 假设 all_data_Number 和 all_data_Rate 已经定义，max_number 和 max_rate 也已经计算好
library(ggplot2)
library(ggsci) # 如果你使用了 ggsci 中的颜色方案

# 确保 year 是数值类型
all_data_Rate$year <- as.numeric(as.character(all_data_Rate$year))
all_data_Number$year <- as.numeric(as.character(all_data_Number$year))

# 筛选出 2021 年之后的数据
post_2021_data <- subset(all_data_Rate, year > 2021)


sf6.5_YLDs <- ggplot() +
  # 添加柱状图表示预测YLDs人数
  geom_bar(data = all_data_Number, aes(x = year, y = val, fill = Type), stat = "identity", position = position_dodge(width = 0.8), alpha = 0.5) +
  # 绘制实际值和预测值的线
  geom_line(data = all_data_Rate, aes(x = year, y = val / max_rate * max_number, color = Type), size = 0.8) +
  # 绘制预测数据的点
  geom_point(data = subset(all_data_Rate, Type == "True value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  geom_point(data = subset(all_data_Rate, Type == "Predicted value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  # 为 2021 年后的数据添加置信区间
  geom_ribbon(data = post_2021_data, aes(x = year, ymin = lower / max_rate * max_number, ymax = upper / max_rate * max_number, fill = Type), alpha = 0.2) +
  scale_y_continuous(name = "YLDs (count)", sec.axis = sec_axis(~. / max_number * max_rate, name = "Age - standardized YLDs rate (per 100,000)")) +
  scale_fill_npg() +  # 使用bmj颜色方案
  scale_color_npg() +  # 使用bmj颜色方案设置线条颜色
  labs(title = "Female",  # 设置标题
       x = " ",  # 设置X轴标签
       y = " ") +  # 设置Y轴标签
  theme_classic() +  # 使用经典主题
  scale_x_continuous(breaks = seq(min(all_data_Rate$year), max(all_data_Rate$year), by = 5)) +
  geom_vline(xintercept = 2021, linetype = "dashed", color = "black") +  # 在2021年的位置添加一条竖直的虚线
  theme(
    legend.position = "top",
    legend.justification = c("left", "top"),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),  # 调整图表标题字体大小
    axis.title.x = element_text(size = 16),  # 调整 X 轴标题字体大小
    axis.title.y = element_text(size = 16),  # 调整 Y 轴标题字体大小
    axis.text.x = element_text(size = 12),  # 调整 X 轴刻度文本字体大小
    axis.text.y = element_text(size = 12),  # 调整 Y 轴刻度文本字体大小
    legend.title = element_text(size = 16),  # 调整图例标题字体大小
    legend.text = element_text(size = 12)  # 调整图例文本字体大小
  )  

# 显示图形
print(sf6.5_YLDs)

ggsave("YLDs_Female预测.tiff",sf6.5_YLDs,height = 6,width = 8,dpi = 600)
# 下载数据
# 保留小数点后两位
all_data_Number1 <- all_data_Number %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Rate1 <- all_data_Rate %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Number预测 <- all_data_Number1  %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
all_data_Rate预测 <- all_data_Rate1 %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
# 选取前两列
all_data_Number预测 <- all_data_Number预测 %>%
  select_at(1:2)
all_data_Rate预测 <- all_data_Rate预测 %>%
  select_at(1:2)
sf6.5_YLDs_Female预测 <- merge(all_data_Number预测, all_data_Rate预测, by = "year")
# 更改列名
sf6.5_YLDs_Female预测 <- sf6.5_YLDs_Female预测 %>%
  rename(Year = year, Number = val.x, Rate = val.y)
write.csv(sf6.5_YLDs_Female预测,"YLDs预测数据（Female）.csv", row.names = FALSE)


#Both
#YLDs预测
#Both
sf6.5_YLDs_Both_Number <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "All ages") %>%
  filter(metric == "Number") %>%
  filter(measure == "YLDs (Years Lived with Disability)") %>%
  filter(sex == "Both") 
#Rate
sf6.5_YLDs_Both_Rate <- combined_data %>%
  filter(location == "China") %>%
  filter(age == "Age-standardized") %>%
  filter(metric == "Rate") %>%
  filter(measure == "YLDs (Years Lived with Disability)") %>%
  filter(sex == "Both") 
#查看数据
str(sf6.5_YLDs_Both_Rate)
str(sf6.5_YLDs_Both_Number)
# 转换年份为数值型
sf6.5_YLDs_Both_Rate$year <- as.numeric(sf6.5_YLDs_Both_Rate$year)
sf6.5_YLDs_Both_Number$year <- as.numeric(sf6.5_YLDs_Both_Number$year)
# 检查并处理缺失值
sf6.5_YLDs_Both_Rate <- na.omit(sf6.5_YLDs_Both_Rate)
sf6.5_YLDs_Both_Number <- na.omit(sf6.5_YLDs_Both_Number)
#按时间进行排序
sf6.5_YLDs_Both_Rate <- sf6.5_YLDs_Both_Rate %>%
  arrange(year)
sf6.5_YLDs_Both_Number <- sf6.5_YLDs_Both_Number %>%
  arrange(year)
# 假设年份是连续的，且数据是按年份排序的
ts_sf6.5_YLDs_Both_Rate <- ts(sf6.5_YLDs_Both_Rate$val, start=c(min(sf6.5_YLDs_Both_Rate$year)), frequency=1)
ts_sf6.5_YLDs_Both_Number <- ts(sf6.5_YLDs_Both_Number$val, start=c(min(sf6.5_YLDs_Both_Number$year)), frequency=1)
# install.packages("forecast")  如果已经安装，可注释掉这行
library(forecast)
fit_Rate <- auto.arima(ts_sf6.5_YLDs_Both_Rate)
fit_Number <- auto.arima(ts_sf6.5_YLDs_Both_Number)
# 预测未来29年
forecast_result_Rate <- forecast(fit_Rate, h=20) 
forecast_result_Number <- forecast(fit_Number, h=20)
plot(forecast_result_Rate)
plot(forecast_result_Number)
library(ggplot2)
# 假设forecast_result是你的预测结果对象
# 首先，我们需要从forecast对象中提取预测值和置信区间
forecast_data_Rate <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Rate$mean,
  upper = forecast_result_Rate$upper[, "80%"],
  lower = forecast_result_Rate$lower[, "80%"]
)
forecast_data_Number <- data.frame(
  year = 2022:2041,  # 假设预测是从2024年开始的20年
  val = forecast_result_Number$mean,
  upper = forecast_result_Number$upper[, "80%"],
  lower = forecast_result_Number$lower[, "80%"]
)
#保留后四列
Both_Rate <- sf6.5_YLDs_Both_Rate[, tail(names(sf6.5_YLDs_Both_Rate), 4)]
Both_Number <- sf6.5_YLDs_Both_Number[, tail(names(sf6.5_YLDs_Both_Number), 4)]
#合并数据
all_data_Rate <- rbind(Both_Rate, forecast_data_Rate)
all_data_Number <- rbind(Both_Number, forecast_data_Number)
# 绘制图表
library(ggplot2)
library(dplyr)
# 假设all_data是包含所有数据的数据框，并且已经包含了区分Actual和Predicted的列
# 如果没有，你需要先创建这个列
all_data_Rate <- all_data_Rate %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
all_data_Number <- all_data_Number %>%
  mutate(Type = ifelse(year >= 1990 & year <= 2021, "True value", "Predicted value"))
max_number <- max(all_data_Number$val, na.rm = TRUE)
max_rate <- max(all_data_Rate$val, na.rm = TRUE)

# 假设 all_data_Number 和 all_data_Rate 已经定义，max_number 和 max_rate 也已经计算好
library(ggplot2)
library(ggsci) # 如果你使用了 ggsci 中的颜色方案

# 确保 year 是数值类型
all_data_Rate$year <- as.numeric(as.character(all_data_Rate$year))
all_data_Number$year <- as.numeric(as.character(all_data_Number$year))

# 筛选出 2021 年之后的数据
post_2021_data <- subset(all_data_Rate, year > 2021)


sf6.5_YLDs <- ggplot() +
  # 添加柱状图表示预测YLDs人数
  geom_bar(data = all_data_Number, aes(x = year, y = val, fill = Type), stat = "identity", position = position_dodge(width = 0.8), alpha = 0.5) +
  # 绘制实际值和预测值的线
  geom_line(data = all_data_Rate, aes(x = year, y = val / max_rate * max_number, color = Type), size = 0.8) +
  # 绘制预测数据的点
  geom_point(data = subset(all_data_Rate, Type == "True value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  geom_point(data = subset(all_data_Rate, Type == "Predicted value"), aes(x = year, y = val / max_rate * max_number), size = 2, shape = 16) +
  # 为 2021 年后的数据添加置信区间
  geom_ribbon(data = post_2021_data, aes(x = year, ymin = lower / max_rate * max_number, ymax = upper / max_rate * max_number, fill = Type), alpha = 0.2) +
  scale_y_continuous(name = "YLDs (count)", sec.axis = sec_axis(~. / max_number * max_rate, name = "Age - standardized YLDs rate (per 100,000)")) +
  scale_fill_npg() +  # 使用bmj颜色方案
  scale_color_npg() +  # 使用bmj颜色方案设置线条颜色
  labs(title = "Both",  # 设置标题
       x = " ",  # 设置X轴标签
       y = " ") +  # 设置Y轴标签
  theme_classic() +  # 使用经典主题
  scale_x_continuous(breaks = seq(min(all_data_Rate$year), max(all_data_Rate$year), by = 5)) +
  geom_vline(xintercept = 2021, linetype = "dashed", color = "black") +  # 在2021年的位置添加一条竖直的虚线
  theme(
    legend.position = "top",
    legend.justification = c("left", "top"),
    plot.title = element_text(hjust = 0.5, face = "bold", size = 16),  # 调整图表标题字体大小
    axis.title.x = element_text(size = 16),  # 调整 X 轴标题字体大小
    axis.title.y = element_text(size = 16),  # 调整 Y 轴标题字体大小
    axis.text.x = element_text(size = 12),  # 调整 X 轴刻度文本字体大小
    axis.text.y = element_text(size = 12),  # 调整 Y 轴刻度文本字体大小
    legend.title = element_text(size = 16),  # 调整图例标题字体大小
    legend.text = element_text(size = 12)  # 调整图例文本字体大小
  )  

# 显示图形
print(sf6.5_YLDs)

ggsave("YLDs_Both预测.tiff",sf6.5_YLDs,height = 6,width = 8,dpi = 600)
# 下载数据
# 保留小数点后两位
all_data_Number1 <- all_data_Number %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Rate1 <- all_data_Rate %>%
  mutate(val = round(val, 3),
         upper = round(upper, 3),
         lower = round(lower, 3))
all_data_Number预测 <- all_data_Number1  %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
all_data_Rate预测 <- all_data_Rate1 %>%
  mutate(val = paste(val, "(", upper, " to ", lower, ")", sep = ""))
# 选取前两列
all_data_Number预测 <- all_data_Number预测 %>%
  select_at(1:2)
all_data_Rate预测 <- all_data_Rate预测 %>%
  select_at(1:2)
sf6.5_YLDs_Both预测 <- merge(all_data_Number预测, all_data_Rate预测, by = "year")
# 更改列名
sf6.5_YLDs_Both预测 <- sf6.5_YLDs_Both预测 %>%
  rename(Year = year, Number = val.x, Rate = val.y)
write.csv(sf6.5_YLDs_Both预测,"YLDs预测数据（Both）.csv", row.names = FALSE)



age_ranges <- c("<20 years", "20-24 years",
                "25-29 years", "30-34 years", "35-39 years", "40-44 years", "45-49 years",
                "50-54 years", "55-59 years", "60-64 years", "65-69 years", "70-74 years",
                "75-79 years", "80-84 years", "85-89 years", "90-94 years", "95+ years")
# 数据筛选和预处理
filtered_data <- combined_data %>%
  filter(sex == "Both") %>%
  filter(location == "China") %>%
  filter(measure == "Prevalence") %>%
  filter(age %in% age_ranges) %>%
  filter(metric == "Rate") %>%
  filter(year %in% c(1990, 2021)) %>%
  mutate(year = factor(year)) %>%
  mutate(age = factor(age,
                      levels = c("<20 years",
                                 "20-24 years", "25-29 years",
                                 "30-34 years", "35-39 years",
                                 "40-44 years", "45-49 years",
                                 "50-54 years", "55-59 years",
                                 "60-64 years", "65-69 years",
                                 "70-74 years", "75-79 years",
                                 "80-84 years", "85-89 years",
                                 "90-94 years", "95+ years")))

# 绘图
df <- ggplot(filtered_data, aes(x = age, y = val, fill = year)) +
  geom_col(position = "dodge", width = 0.8) +
  geom_errorbar(aes(ymin = lower, ymax = upper, color = year), position = "dodge", width = 0.8) +
  labs(x = "", y = "Prevalence rate(per 100,000)", title = "") +
  theme_bw() +theme_classic() +  # 使用经典主题 # 使用bmj颜色方案设置线条颜色
  theme(
    # 调整主标题字体大小
    plot.title = element_text(size = 14, face = "bold", hjust = 0.5), 
    # 调整 x 轴标签字体大小
    axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, size = 12), 
    # 调整 y 轴标签字体大小
    axis.text.y = element_text(size = 12), 
    # 调整 x 轴标题字体大小
    axis.title.x = element_text(size = 14), 
    # 调整 y 轴标题字体大小
    axis.title.y = element_text(size = 14), 
    # 调整图例位置
    legend.position = c(1, 1),
    # 调整图例对齐方式
    legend.justification = c(1, 1),
    # 去除图例背景
    legend.background = element_blank(),
    # 调整图例标题字体大小
    legend.title = element_text(size = 14), 
    # 调整图例文本字体大小
    legend.text = element_text(size = 12) 
  )

# 显示图表
print(df)
ggsave("图3.tiff",df,width = 8,height = 6,dpi = 600)


#ylds
filtered_data <- combined_data %>%
  filter(sex == "Both") %>%
  filter(location == "China") %>%
  filter(measure == "YLDs (Years Lived with Disability)") %>%
  filter(age %in% age_ranges) %>%
  filter(metric == "Rate") %>%
  filter(year %in% c(1990, 2021)) %>%
  mutate(year = factor(year)) %>%
  mutate(age = factor(age,
                      levels = c("<20 years",
                                 "20-24 years", "25-29 years",
                                 "30-34 years", "35-39 years",
                                 "40-44 years", "45-49 years",
                                 "50-54 years", "55-59 years",
                                 "60-64 years", "65-69 years",
                                 "70-74 years", "75-79 years",
                                 "80-84 years", "85-89 years",
                                 "90-94 years", "95+ years")))

# 绘图
df <- ggplot(filtered_data, aes(x = age, y = val, fill = year)) +
  geom_col(position = "dodge", width = 0.8) +
  geom_errorbar(aes(ymin = lower, ymax = upper, color = year), position = "dodge", width = 0.8) +
  labs(x = "", y = "YLDs (Years Lived with Disability) rate(per 100,000)", title = "") +
  theme_bw() +theme_classic() +  # 使用经典主题 # 使用bmj颜色方案设置线条颜色
  theme(
    # 调整主标题字体大小
    plot.title = element_text(size = 14, face = "bold", hjust = 0.5), 
    # 调整 x 轴标签字体大小
    axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, size = 12), 
    # 调整 y 轴标签字体大小
    axis.text.y = element_text(size = 12), 
    # 调整 x 轴标题字体大小
    axis.title.x = element_text(size = 14), 
    # 调整 y 轴标题字体大小
    axis.title.y = element_text(size = 14), 
    # 调整图例位置
    legend.position = c(1, 1),
    # 调整图例对齐方式
    legend.justification = c(1, 1),
    # 去除图例背景
    legend.background = element_blank(),
    # 调整图例标题字体大小
    legend.title = element_text(size = 14), 
    # 调整图例文本字体大小
    legend.text = element_text(size = 12) 
  )

# 显示图表
print(df)
ggsave("图4.tiff",df,width = 8,height = 6,dpi = 600)



data21 <-combined_data |>
  filter(measure=="Prevalence") |>
  filter(location=="China")|>
  filter(year=="2021") |>
  filter(sex!="Both") |>
  filter(age %in%  c("<20 years" , "20-24 years",
                     "25-29 years", "30-34 years", "35-39 years", "40-44 years", "45-49 years",
                     "50-54 years", "55-59 years", "60-64 years", "65-69 years", "70-74 years",
                     "75-79 years", "80-84 years", "85-90 years", "90-94 years", "95+ years")) |>
  filter(metric %in% c("Number","Rate"))
data21
unique(data21$age)
# 假设你的数据框叫做df
# 首先，我们需要将数据框转换为长格式，以便于使用ggplot2绘图
data21_long <- data21 %>%
  pivot_longer(cols = starts_with("val"), names_to = "type", values_to = "value") %>%
  mutate(age = factor(age, levels = c("<20 years" , "20-24 years",
                                      "25-29 years", "30-34 years", "35-39 years", "40-44 years", "45-49 years",
                                      "50-54 years", "55-59 years", "60-64 years", "65-69 years", "70-74 years",
                                      "75-79 years", "80-84 years", "85-90 years", "90-94 years", "95+ years")),
         sex = factor(sex, levels = c("Male", "Female", "Both")))
str(data21_long)
data21_long$value <- as.numeric(as.character(data21_long$value))
str(data21_long)# 确保value是数值型
data21_long$upper <- as.numeric(as.character(data21_long$upper))
data21_long$lower <- as.numeric(as.character(data21_long$lower))
# 计算number和rate的最大值，用于缩放
max_number <- max(data21_long$value[data21_long$metric == "Number" & data21_long$sex != "Both"], na.rm = TRUE)
max_rate <- max(data21_long$value[data21_long$metric == "Rate" & data21_long$sex != "Both"], na.rm = TRUE)
# 绘制双y轴复合柱状折线图
# 绘制双y轴复合柱状折线图
pic22 <- ggplot(data21_long, aes(x = age, color = sex, fill = sex)) +
  geom_bar(data = subset(data21_long, metric == "Number" & sex != "Both"), aes(y = value), stat = "identity", position = position_dodge(0.8)) +
  geom_smooth(data = subset(data21_long, metric == "Rate" & sex != "Both"), aes(y = value / max_rate * max_number, group = sex, color = sex), method = "loess", se = TRUE, position = position_dodge(0.8)) +
  geom_errorbar(data = subset(data21_long, metric == "Number" & sex != "Both"), aes(y = value, ymin = lower, ymax = upper), width = 0.2, position = position_dodge(0.8)) +
  scale_y_continuous(name = "Prevalence (count)", sec.axis = sec_axis(~ . / max_number * max_rate, name = "Prevalence rate (per 100,000)")) +
  labs(title = "",
       x = "",
       y = "Prevalence (count)",
       color = "Sex",
       fill = "Sex") +
  theme_classic() +
  scale_color_nejm() +
  theme(
    # 调整主标题字体大小
    plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
    # 调整 x 轴标签字体大小
    axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, size = 12),
    # 调整 y 轴标签字体大小
    axis.text.y = element_text(size = 12),
    # 调整 x 轴标题字体大小
    axis.title.x = element_text(size = 14),
    # 调整 y 轴标题字体大小
    axis.title.y = element_text(size = 14),
    # 调整副 y 轴标题字体大小
    axis.title.y.right = element_text(size = 14),
    # 调整图例标题字体大小
    legend.title = element_text(size = 14),
    # 调整图例文本字体大小
    legend.text = element_text(size = 12),
    # 调整图例位置
    legend.position = "top",
    # 调整图例对齐方式
    legend.justification = "top"
  )

# 显示图表
print(pic22)
ggsave("China不同性别随年龄变化趋势2021.tiff",pic22, width = 8, height = 6, dpi = 600)



#G20
data21 <-combined_data |>
  filter(measure=="Prevalence") |>
  filter(location=="G20")|>
  filter(year=="2021") |>
  filter(sex!="Both") |>
  filter(age %in%  c("<20 years" , "20-24 years",
                     "25-29 years", "30-34 years", "35-39 years", "40-44 years", "45-49 years",
                     "50-54 years", "55-59 years", "60-64 years", "65-69 years", "70-74 years",
                     "75-79 years", "80-84 years", "85-90 years", "90-94 years", "95+ years")) |>
  filter(metric %in% c("Number","Rate"))
data21
unique(data21$age)
# 假设你的数据框叫做df
# 首先，我们需要将数据框转换为长格式，以便于使用ggplot2绘图
data21_long <- data21 %>%
  pivot_longer(cols = starts_with("val"), names_to = "type", values_to = "value") %>%
  mutate(age = factor(age, levels = c("<20 years" , "20-24 years",
                                      "25-29 years", "30-34 years", "35-39 years", "40-44 years", "45-49 years",
                                      "50-54 years", "55-59 years", "60-64 years", "65-69 years", "70-74 years",
                                      "75-79 years", "80-84 years", "85-90 years", "90-94 years", "95+ years")),
         sex = factor(sex, levels = c("Male", "Female", "Both")))
str(data21_long)
data21_long$value <- as.numeric(as.character(data21_long$value))
str(data21_long)# 确保value是数值型
data21_long$upper <- as.numeric(as.character(data21_long$upper))
data21_long$lower <- as.numeric(as.character(data21_long$lower))
# 计算number和rate的最大值，用于缩放
max_number <- max(data21_long$value[data21_long$metric == "Number" & data21_long$sex != "Both"], na.rm = TRUE)
max_rate <- max(data21_long$value[data21_long$metric == "Rate" & data21_long$sex != "Both"], na.rm = TRUE)
# 绘制双y轴复合柱状折线图
# 绘制双y轴复合柱状折线图
pic22 <- ggplot(data21_long, aes(x = age, color = sex, fill = sex)) +
  geom_bar(data = subset(data21_long, metric == "Number" & sex != "Both"), aes(y = value), stat = "identity", position = position_dodge(0.8)) +
  geom_smooth(data = subset(data21_long, metric == "Rate" & sex != "Both"), aes(y = value / max_rate * max_number, group = sex, color = sex), method = "loess", se = TRUE, position = position_dodge(0.8)) +
  geom_errorbar(data = subset(data21_long, metric == "Number" & sex != "Both"), aes(y = value, ymin = lower, ymax = upper), width = 0.2, position = position_dodge(0.8)) +
  scale_y_continuous(name = "Prevalence (count)", sec.axis = sec_axis(~ . / max_number * max_rate, name = "Prevalence rate (per 100,000)")) +
  labs(title = "",
       x = "",
       y = "Prevalence (count)",
       color = "Sex",
       fill = "Sex") +
  theme_classic() +
  scale_color_nejm() +
  theme(
    # 调整主标题字体大小
    plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
    # 调整 x 轴标签字体大小
    axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1, size = 12),
    # 调整 y 轴标签字体大小
    axis.text.y = element_text(size = 12),
    # 调整 x 轴标题字体大小
    axis.title.x = element_text(size = 14),
    # 调整 y 轴标题字体大小
    axis.title.y = element_text(size = 14),
    # 调整副 y 轴标题字体大小
    axis.title.y.right = element_text(size = 14),
    # 调整图例标题字体大小
    legend.title = element_text(size = 14),
    # 调整图例文本字体大小
    legend.text = element_text(size = 12),
    # 调整图例位置
    legend.position = "top",
    # 调整图例对齐方式
    legend.justification = "top"
  )

# 显示图表
print(pic22)
ggsave("G20不同性别随年龄变化趋势2021.tiff",pic22, width = 8, height = 6, dpi = 600)
