# Tạo dataframe for
f<- data.frame(
  variable = c("Dyspnea", "Lower airway obstruction syndrome", "Respiratory infection syndrome", 
               "Mediastinal lymph node", "Pleural invasion", "Mediastinal invasion", 
               "Exophytic tumor", "Left upper lobe bronchus (bronchoscopy)", "Biopsy site"),
  OR = c(1.8, 3.979, 0.49, 2.05, 5.997, 0.61, 1.58, 5.563, 4.967),
  lowerCI = c(0.55, 1.313, 0.13, 0.68, 1.444, 0.14, 0.33, 1.806, 1.746),
  upperCI = c(6.23, 12.922, 1.74, 6.32, 28.472, 2.45, 7.24, 18.72, 15.213),
  pvalue = c("", 0.1675, "", "", 0.01655, "", "", 0.00368, 0.0034),
  sign = c("No", "Yes", "No", "No", "Yes", "No", "No", "Yes", "Yes")
)

# Xem dữ liệu
print(f)
##                                  variable    OR lowerCI upperCI  pvalue sign
## 1                                 Dyspnea 1.800   0.550   6.230           No
## 2       Lower airway obstruction syndrome 3.979   1.313  12.922  0.1675  Yes
## 3          Respiratory infection syndrome 0.490   0.130   1.740           No
## 4                  Mediastinal lymph node 2.050   0.680   6.320           No
## 5                        Pleural invasion 5.997   1.444  28.472 0.01655  Yes
## 6                    Mediastinal invasion 0.610   0.140   2.450           No
## 7                         Exophytic tumor 1.580   0.330   7.240           No
## 8 Left upper lobe bronchus (bronchoscopy) 5.563   1.806  18.720 0.00368  Yes
## 9                             Biopsy site 4.967   1.746  15.213  0.0034  Yes
# Cài đặt gói nếu chưa có
#install.packages("ggplot2")  

# Tải thư viện ggplot2
library(ggplot2)

# Chuyển cột "sign" thành factor để sắp xếp
f$sign <- factor(f$sign, levels = c("Yes", "No"))

# Sắp xếp dữ liệu: biến "Yes" lên trước, sau đó là "No"
f <- f[order(f$sign, decreasing = TRUE), ]

# Vẽ biểu đồ forest plot
ggplot(f, aes(y = reorder(variable, OR), x = OR, color = sign, shape = sign)) +
  geom_pointrange(aes(xmin = lowerCI, xmax = upperCI), size = 1) + # Khoảng tin cậy
  geom_point(size = 1) +  # Kích thước điểm OR
  scale_color_manual(values = c("Yes" = "blue", "No" = "gray")) +  # Màu sắc
  scale_shape_manual(values = c("Yes" = 17, "No" = 16)) +  # Hình tam giác (17) và tròn (16)
  geom_vline(xintercept = 1, linetype = "dashed", color = "red") +  # Đường tham chiếu OR = 1
  labs(x = "Odds Ratio (OR)", y = "Variable", title = "Forest Plot of OR with 95% CI") +
  theme_minimal() +  
  theme(legend.position = "bottom", legend.title = element_blank(), text = element_text(size = 14))+ 
  geom_text(aes(label = paste0("OR = ", round(OR, 2))), 
            hjust = -0.2, vjust = -0.5, size = 3, color = "gray40")