【问题标题】:R: Remove text in ggplot2 bar plot if value is less than a threshholdR:如果值小于阈值,则删除 ggplot2 条形图中的文本
【发布时间】:2022-06-15 19:49:20
【问题描述】:

我有以下情节:

df <- tibble(days = c(1, 1, 2, 2),
         type = c("v1", "v2", "v1", "v2"),
         values = c(100, 1, 2, 200))
plot <-  df %>%
  ggplot(aes(days, values, fill = factor(type))) + 
  geom_bar(stat = 'identity',  position = 'dodge') + 
  geom_text(aes(label = values), vjust=1.6, color="white", position = position_dodge(0.9), size=3.5)
plot

如果相应的值大于特定阈值,有没有办法只在条上添加文本。在这种情况下,我想删除文本“1”和“2”(蓝色圆圈)。

【问题讨论】:

  • 在调用 ggplot 之前过滤,类似于:df %&gt;% filter(values &gt;5) %&gt;% ggplot(....

标签: r ggplot2


【解决方案1】:

geom_text 使用一个新变量,如果在阈值之下,您将其设置为NA

library(ggplot2)
library(tidyverse)
df <- tibble(days = c(1, 1, 2, 2),
         type = c("v1", "v2", "v1", "v2"),
         values = c(100, 1, 2, 200))
tresh <- 100
df$text <- ifelse(df$values < tresh, NA, df$values)

plot <-  df %>%
  ggplot(aes(days, values, fill = factor(type))) + 
  geom_bar(stat = 'identity',  position = 'dodge') + 
  geom_text(aes(label = text), vjust=1.6, color="white", position = position_dodge(0.9), size=3.5)
plot

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2022-11-14
    相关资源
    最近更新 更多