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

Time:05-15

I would like the title of my plot to change based on if the supply is over or under the estimate. The estimate of the supply is in DF$Supply.. If it is positive its over the estimate and if it is negative it's under the estimate. How can i set up the condition to check the DF$Supply and chose the right title.

If the supply is OVER the estimate i would like the title to be this:

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

If the supply is UNDER the estimate i would like the title to be this:

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

If the supply is equal to the estimate the title is (this means that DF$Supply = 0):

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

CodePudding user response:

Im not sure if this is going to work, its always better when you provide the dataset...

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"
    ))

CodePudding user response:

You can set up the title of the plot prior to plotting, like this:

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")
)

Then, within your ggplot call, you can do can simply:

labs(title=plot_title)
  • Related