首页 > 解决方案 > 在 pec 对象的图中更改图例的位置

问题描述

我正在尝试从 pec 包中绘制预测误差曲线,但我无法更改图例的位置和大小。有一个来自 pec 包的例子:

library(rms)
library(pec)
data(pbc)
pbc <- pbc[sample(1:NROW(pbc),size=100),]
f1 <- psm(Surv(time,status!=0)~edema+log(bili)+age+sex+albumin,data=pbc)
f2 <- coxph(Surv(time,status!=0)~edema+log(bili)+age+sex+albumin,data=pbc,x=TRUE,y=TRUE)
f3 <- cph(Surv(time,status!=0)~edema+log(bili)+age+sex+albumin,data=pbc,surv=TRUE)
brier <- pec(list("Weibull"=f1,"CoxPH"=f2,"CPH"=f3),data=pbc,formula=Surv(time,status!=0)~1)
print(brier)
plot(brier)

却在剧情中展现了一个大传奇。

在此处输入图像描述

我也试过:

plot(brier, legend = "topright")
class(brier)

但不要显示传奇。

在此处输入图像描述

如何更改图例的位置?还有 ¿ 是否可以使用 ggplot 绘制此图?

标签: rggplot2

解决方案


我想我得到了你想要的东西ggplot2。这个想法是从包含绘图数据的对象中挑选元素,brier用它制作一个数据框并绘制它。

library(ggplot2)
# packages for the pipe and pivot_wider, you can do it with base functions, I just prefer these
library(tidyr)
library(dplyr)

df <- do.call(cbind, brier[["AppErr"]]) # contains y values for each model
df <- cbind(brier[["time"]], df) # values of the x axis
colnames(df)[1] <- "time"             
df <- as.data.frame(df) %>% pivot_longer(cols = 2:last_col(), names_to = "models", values_to = "values") # pivot table to long format makes it easier to use ggplot

ggplot(data = df, aes(x = time, y = values, color = models)) +
  geom_line() # I suppose you know how to custom axis names etc. 

输出:

在此处输入图像描述


推荐阅读