使用ggsurvplot自定义字体

sdnqo3pr  于 2023-04-18  发布在  其他
关注(0)|答案(2)|浏览(445)

我想将ggsurvplot()图中所有文本的字体更改为Proxima Nova,该字体保存在我的本地计算机上。我已使用showtext包将该字体导入R,但我不确定如何调整ggsurvplot()代码以接受ggtheme之外的字体

library(showtext)

font_add("proxima", "~/Library/Fonts/Proxima\ Nova\ Font.otf")

ggsurvplot(
  surv_fit,
  data = df,
  title = "Survival by Neighborhood SES",
  xlab = "Time since hospital discharge (years)",
  ylab = "Survival Probability",
  legend.title = "Neighborhood",
  legend.labs = c("Prosperous", "Comfortable", "Mid-Tier", "At-Risk", "Distressed"),
  font.legend = 9,
  conf.int = FALSE,
  censor = FALSE,
  surv.scale = "percent",
  break.time.by = 2,
  pval = T,
  palette = c("#FFE082", "#FFB300", "#FF8F00", "#EF5350", "#B71C1C"),
  ggtheme = theme_classic()
) +
    theme(
      text = element_text(family = "proxima")
    )

当我添加theme行时,我得到错误Error in ggsurvplot(surv_fit, data = df, title = "Survival by Neighborhood SES", : non-numeric argument to binary operator In addition: Warning message: Incompatible methods ("+.ggsurv", "+.gg") for "+"
我已经尝试调整font.family,但它似乎无法识别我的首选字体。我应该使用其他包来自定义字体吗?我如何调整代码以使用我用showtext加载的字体?

ukdjmx9f

ukdjmx9f1#

使用自定义字体
ggsurvplot()
和showtext,您可以修改图的主题参数。您可以添加一个showtext主题,指定图中所有文本使用的字体系列,如下例所示:

library(showtext)
library(survminer)

# Import font
font_add("proxima", "~/Library/Fonts/Proxima\ Nova\ Font.otf")

# Create showtext theme
proxima_theme <- theme(
  text = element_text(family = "proxima")
)

# Plot with custom font
ggsurvplot(
  surv_fit,
  data = df,
  title = "Survival by Neighborhood SES",
  xlab = "Time since hospital discharge (years)",
  ylab = "Survival Probability",
  legend.title = "Neighborhood",
  legend.labs = c("Prosperous", "Comfortable", "Mid-Tier", "At-Risk", "Distressed"),
  font.legend = 9,
  conf.int = FALSE,
  censor = FALSE,
  surv.scale = "percent",
  break.time.by = 2,
  pval = T,
  palette = c("#FFE082", "#FFB300", "#FF8F00", "#EF5350", "#B71C1C"),
  ggtheme = theme_classic() + proxima_theme # Add custom theme
)

在上面的示例中,我们首先使用font_add()showtext包中导入Proxima Nova字体。然后使用theme()创建自定义主题,为图中的所有文本指定proxima字体家族。最后使用**+操作符将自定义主题添加到ggsurvplot()ggtheme参数中。
需要注意的是,我们使用
+而不是%+%来将自定义主题添加到ggtheme参数中,这是因为showtext就地修改了ggplot2主题对象,这意味着应该使用+运算符而不是%+%**,以避免兼容性问题。

jckbn6z7

jckbn6z72#

明白了!看起来如果你调整ggtheme行,你可以添加自定义字体:

ggtheme = theme_classic(base_family = "proxima"),
   font.family = "proxima"

相关问题