在底部发布的代码中,我尝试向现有图例添加一个带有标签“置信区间”的灰色条。有人可以帮我将其添加到图例中吗?如果这可以添加到现有的传说中,那就太好了;如果只为这个项目添加一个新的图例更清晰,那也可以。作为旁注,对于渲染的简单绘图,我的 ggplot 代码看起来相当长且混乱,也许这就是 ggplot 代码总是最终的结果。我想知道 ggplot 与基本 R 图相比是否值得。
代码:
library(dplyr)
library(ggplot2)
library(MASS)
library(survival)
lung1 <- lung %>%
mutate(time1 = ifelse(time >= 500, 500, time)) %>%
mutate(status1 = ifelse(status == 2 & time >= 500, 1, status))
weibCurve <- function(time, survregCoefs) {exp(-(time/exp(survregCoefs[1]))^exp(-survregCoefs[2]))}
fit1 <- survreg(Surv(time1, status1) ~ 1, data = lung1)
lung1.survfit <- survfit(Surv(time1, status1) ~ 1, data = lung1)
lung1.df <- data.frame(time = lung1.survfit$time,
survival = lung1.survfit$surv,
upper_95 = lung1.survfit$upper,
lower_95 = lung1.survfit$lower)
lung1.df %>%
ggplot(aes(x = time, y = survival)) +
geom_ribbon(aes(ymin = lower_95, ymax = upper_95), alpha = 0.2, fill = "grey") +
geom_line(aes(y = survival, color = "Historical data"), size = 1) +
scale_x_continuous(limits = c(0, 1500)) +
scale_y_continuous(limits = c(0, 1), expand = c(0, 0.05)) +
labs(x = "Time", y = "Fraction surviving", color = NULL) +
theme_classic() +
stat_function(fun = weibCurve, args = list(survregCoefs = fit1$icoef),
aes(color = "Weibull distribution fit"), size = 1, n = 1000) +
scale_color_manual(values = c("blue", "red", "grey"),
labels = c("Historical data", "Weibull distribution fit", "Confidence intervals")) +
labs(color = NULL) +
theme(legend.position = c(0.95, 0.95), legend.justification = c(1, 1),
legend.title.align = 0.5, legend.box.spacing = unit(0.3, "lines"),
legend.margin = margin(t = 0, r = 0, b = 0, l = 0), legend.title = element_text(size = 12),
legend.text = element_text(size = 10))
Run Code Online (Sandbox Code Playgroud)
如果我们将丝带的填充映射到fill美学上,我们可以显示像您的图片一样的图例条目。要控制分配给该填充的颜色,我们可以使用scale_fill_manual,并且可以使用 将填充图例放在颜色图例之后guide_legend(order = ...)。
...
geom_ribbon(aes(ymin = lower_95, ymax = upper_95, fill = "Confidence Interval"),
alpha = 0.2) +
scale_fill_manual(values = c("Confidence Interval" = "grey50"), name = NULL) +
guides(color = guide_legend(order = 1), fill = guide_legend(order = 2)) +
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |