如何根据条件更改图表标题中的单词?

How to changes words in a charts title based on condition?

我希望根据供应量是高于还是低于估计值来更改我的地块的标题。供应量的估计以 DF$Supply 为单位。如果它是正的,它就高于估计,如果它是负的,它就低于估计。我如何设置条件来检查 DF$Supply 并选择正确的标题。

如果供应超过估计,我希望标题是这样的:

labs(title=paste("In 2021-2030 the supply is over the estimate by", DF$Supply)

如果供应低于估计,我希望标题是这样的:

labs(title=paste("In 2021-2030 the supply is under the estimate by", DF$Supply*-1)

如果供应量等于标题的估计值(这意味着 DF$Supply = 0):

labs(title="In 2021-2030 the supply matches the estimate")

我不确定这是否可行,提供数据集总是更好...

labs(title = case_when(
      DF$Supply >= 1 ~ paste("In 2021-2030 the supply is over the estimate by", DF$Supply),
      DF$Supply < 0 ~ paste("In 2021-2030 the supply is under the estimate by", DF$Supply*-1),
      DF$Supply == 0 ~ "In 2021-2030 the supply matches the estimate"
    ))

您可以在绘图前设置绘图标题,如下所示:

plot_title <-  "In 2021-2030 the supply "

plot_title <- dplyr::case_when(
  DF$Supply>0~paste0(plot_title, "is over the estimate by ", DF$Supply),
  DF$Supply<0~paste0(plot_title, "is under the estimate by ", DF$Supply*-1),
  TRUE~paste0(plot_title, "matches the estimate")
)

然后,在你的 ggplot 调用中,你可以简单地做:

labs(title=plot_title)