我使用survival程序包按组对生存曲线进行Kaplan-Mayer估计,然后使用ggfortifysurvminer程序包绘制出上述曲线.除用于打印的图例标签外,所有标签均工作正常.我想在图例标签中显示N个大小的组.我认为使用paste0将N大小添加到GROUPING变量本身是一个不错的方法.在我的情况下,它比使用像scale_fill_discrete("", labels = legend_labeller_for_plot)这样的东西更容易.

library(dplyr)
library(ggplot2)
library(survival)
library(survminer)
library(ggfortify)


set.seed = 100
data <- data.frame(
  time = rlnorm(20),
  event = as.integer(runif(20) < 0.5),
  group = ifelse(runif(20) > 0.5,
                 "group A",
                 "group B")
)

# Plotting survival curves without N sizes in the legend
fit <- survfit(
  with(data, Surv(time, event)) ~ group,
  data)

autoplot(fit)

# Adding N sizes to the data and plotting
data_new <- data %>% 
  group_by(group) %>% mutate(N = n()) %>% 
  ungroup() %>% 
  mutate(group_with_N = paste0(group, ", N = ", N))

fit_new <- survfit(
  with(data, Surv(time, event)) ~ group_with_N,
  data_new)

autoplot(fit_new)

When I try to add N sizes to the groups variable, the part with "N =" in the grouping variable disappears, i.e. the group variable isn't displayed on the legend labels as expected.enter image description here

For comparison, what I expect is something like the following using Iris data: enter image description here

更重要的是,我发现罪魁祸首是等号=.当我go 掉=号时,图例标签对应于分组变量值. 我的问题是,为什么等号会导致这种情况?

推荐答案

一个选项可以是使用ggsurvplot,其中您可以指定legend.labs,这样您就可以在图例中显示您的尺寸,如下所示:

library(dplyr)
library(ggplot2)
library(survival)
library(survminer)
library(ggfortify)

set.seed = 100
data <- data.frame(
  time = rlnorm(20),
  event = as.integer(runif(20) < 0.5),
  group = ifelse(runif(20) > 0.5,
                 "group A",
                 "group B")
)

# Adding N sizes to the data and plotting
data_new <- data %>% 
  group_by(group) %>% mutate(N = n()) %>% 
  ungroup() %>% 
  mutate(group_with_N = paste0(group, ", N = ", N))

fit_new <- survfit(
  with(data, Surv(time, event)) ~ group_with_N,
  data_new)

p <- autoplot(fit_new)
p

# ggsurvplot
ggsurvplot(fit_new, data_new, 
           legend.labs = unique(sort(data_new$group_with_N)),
           conf.int = TRUE)

创建于2022-08-18,共reprex v2.0.2

R相关问答推荐

R中的滞后累积量

分组时间连续值

是否有任何解决方案可以优化VSCode中RScript的图形绘制?

高质量地将R格式的图表从Word中输出

如何在四进制仪表板值框中显示值(使用shiny 的服务器计算)

在R底座中更改白天和夜晚的背景 colored颜色

从gtsummary包中使用tBL_strata()和tBL_summary()时删除变量标签

使用tidyverse方法绑定行并从一组管道列表执行左连接

selectInput不返回ALL,并将因子转换为shiny 的数字

derrr summarise每个组返回多行?

ggplot的轴标签保存在officer中时被剪切

如何从R ggplot图片中获取SVG字符串?

使用rvest从多个页面抓取时避免404错误

当我添加美学时,geom_point未对齐

从数据创建数字的命名列表.R中的框

R中时间间隔的大向量与参考时间间隔的相交

创建新列,其中S列的值取决于该行S值是否与其他行冗余

使用函数从R中的列中删除标高

R try Catch in the loop-跳过缺少的值并创建一个DF,显示跳过的内容

R中从因数到数字的转换