首页 > 解决方案 > 在特定的 ggplots 中添加一个百分比符号来标记,而不是在其他图中

问题描述

我有一个闪亮的应用程序,有多个 ggplot,很少显示百分比标签其他四舍五入的数字。所有都由创建 ggplot 的相同函数返回。percent_flag作为参数传递给相同的函数。我尝试了以下逻辑,但它不起作用。我没有选择创建额外的列来满足条件。

geom_text(aes(label = ifelse(percent_flag == 1,
                             paste(round(BIAS_contribution, 2), "%", sep = ""),
                             comma(BIAS_contribution)),
              y = (start + end) / 2)

标签: rggplot2

解决方案


我建议使用基本的 if 子句:

library(ggplot2)
percent_flag <- 1

# base plot
p <- iris %>% 
  ggplot(aes(x = Sepal.Length, y = Sepal.Width))

# with percent flag
if(percent_flag == 1){
  p2 <- p +
  geom_text(aes(label = paste0(Petal.Width, "%")))
  
  # withput percent flag
} else {
  p2 <- p +
    geom_text(aes(label = Petal.Width))
}
p2

推荐阅读