我已經調整了解決方案來對齊森林圖和這篇文章中的表格:
如何將表格與森林圖對齊(ggplot2)
這是我的代碼:
library(dplyr, warn = FALSE)
library(ggplot2)
library(patchwork)
tester <- data.frame(
treatmentgroup = c("Education Continuous", "0", "1-4",
"5-8", ">8"),
or = c(0.914, 0.961, 0.709, 0.523, 0.457),
low_ci = c(0.894, 0.793, 0.577, 0.389, 0.339),
up_ci = c(0.935, 1.166, 0.871, 0.708, 0.616),
OR_ci = c(
"0.914 (0.894; 0.935)", "0.961 (0.793; 1.166)", "0.709 (0.577; 0.871)",
"0.523 (0.389; 0.708)", "0.457 (0.339; 0.616)"),
ci = c(
"0.894; 0.935",
"0.793; 1.166",
"0.577; 0.871",
"0.389; 0.708",
"0.339; 0.616"),
no = c(1, 2, 3, 4, 5)
)
forest <- ggplot(
data = tester,
aes(x = treatmentgroup, y = or, ymin = low_ci, ymax = up_ci))
geom_pointrange(aes(col = treatmentgroup))
geom_hline(yintercept = 1, colour = "black")
xlab("")
ylab("OR (95% CI)")
geom_errorbar(aes(ymin = low_ci, ymax = up_ci, col = treatmentgroup), width = 0, cex = 1)
theme_classic()
theme(
panel.background = element_blank(), strip.background = element_rect(colour = NA, fill = NA),
strip.text.y = element_text(face = "bold", size = 12),
panel.grid.major.y = element_line(colour = col_grid, size = 0.5),
strip.text = element_text(face = "bold"),
panel.border = element_rect(fill = NA, color = "black"),
legend.position = "none",
axis.text = element_text(face = "bold"),
axis.title = element_text(face = "bold"),
plot.title = element_text(face = "bold", hjust = 0.5, size = 13)
)
coord_flip()
dat_table <- tester %>%
select(treatmentgroup, OR_ci) %>%
tidyr::pivot_longer(c(OR_ci), names_to = "stat") %>%
mutate(stat = factor(stat, levels = "OR_ci"))
table_base <- ggplot(dat_table, aes(stat, treatmentgroup, label = value))
geom_text(size = 3)
scale_x_discrete(position = "top", labels = "OR (95% CI)")
labs(y = NULL, x = NULL)
theme_classic()
theme(
strip.background = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_blank(),
axis.line = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_text(size = 12),
axis.ticks = element_blank(),
axis.title = element_text(face = "bold"),
)
forest table_base plot_layout(widths = c(10, 4))
但是,我的圖表以無序的類別結束。如何將順序調整為以下順序:Education Continuous、0、1-4、5-8 和 >8?
我試過 factor(tester$treatmentgroup)了,但沒有用。
另外,如何使所有類別的顏色相同(例如黑色)而不是每種顏色一個?我嘗試消除這條線geom_pointrange(aes(col = treatmentgroup)) ,但它不起作用。
uj5u.com熱心網友回復:
你是對的,你可以轉換treatmentgroup為一個因子,你只需要指定級別。在生成繪圖之前嘗試運行此代碼ggplot()。
tester <- tester %>%
mutate(treatmentgroup = factor(treatmentgroup,
levels = c(">8", "5-8", "1-4", "0", "Education Continuous")))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/530802.html
標籤:rggplot2
