【问题标题】:How to label minimum value in each x step axis in R (ggplot) library如何在 R(ggplot)库中的每个 x 步长轴中标记最小值
【发布时间】:2025-12-21 17:25:16
【问题描述】:

我正在用 geom_text_repel 库绘制 ggplot。 x 轴是个人 ID,y 轴是连续值。

如何在 x 轴的每个步骤中添加标签最小 y 值。 这是我的简单代码。

dummy_plot = ggplot(data = summary_mmdata ,
                aes(x = factor(type),y = WER_Value,
                    linetype=factor(WER_Type),
                    shape = factor(method),
                    group =factor(WER_Type):factor(method)
                )) +


geom_line()+
  geom_point()+
  scale_y_log10()+
  scale_shape_discrete(name = "",
                       labels=c("Test_Distance"="D1","Test_DistanceV2"="D2T",
                                "Test_DistanceV2MAV"="D2M","Test_DistanceV2Skip2"="D2S",
                                "Test_HeatMap"="HM"))+

  ylab("AER")+
  xlab("")+
  geom_text_repel(
    data = subset(summary_mmdata, WER_Value == min(WER_Value)),
    aes(label = WER_Value),
    size = 5,
    box.padding = unit(0.35, "lines"),
    point.padding = unit(0.3, "lines")
  )

dummy_plot

我使用了 geom_text_repel 库。它仅标记最小值。我想要 x 轴上的所有每一步。请给我提意见。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这是一个使用mtcars 数据集的可重现示例。我将geom_text_regel 的数据输入分组,然后保留最小值并用“”覆盖所有其他值,这不会为这些观察结果生成标签:

    mtcars %>% 
      ggplot(aes(x = factor(gear), y = mpg))+
      geom_line()+
      geom_point()+
      scale_y_log10()+
      scale_shape_discrete(name = "",
                           labels=c("Test_Distance"="D1","Test_DistanceV2"="D2T",
                                    "Test_DistanceV2MAV"="D2M","Test_DistanceV2Skip2"="D2S",
                                    "Test_HeatMap"="HM"))+
      ylab("AER")+
      xlab("")+
      geom_text_repel(
        data = mtcars %>% group_by(gear) %>% mutate(label_var = if_else(mpg == min(mpg), as.character(min(mpg)), "")),
        aes(label = label_var),
        size = 5,
        box.padding = unit(0.35, "lines"),
        point.padding = unit(0.3, "lines")
      )
    
    
    

    所以在你的情况下,我认为这应该可行:

    geom_text_repel(
      data = summary_mmdata %>% group_by(type) %>% mutate(WER_VALUE = if_else(WER_VALUE == min(WER_VALUE), as.character(min(WER_VALUE)), "")),
      aes(label = label_var),
      size = 5,
      box.padding = unit(0.35, "lines"),
      point.padding = unit(0.3, "lines")
    )
    

    【讨论】: