代码之家  ›  专栏  ›  技术社区  ›  Pisit Nakjai

如何在R(ggplot)库中标记每个x步进轴中的最小值

  •  0
  • Pisit Nakjai  · 技术社区  · 4 年前

    我正在用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轴上的每一步。请给我建议。 enter image description here

    1 回复  |  直到 4 年前
        1
  •  1
  •   Dominik S. Meier    4 年前

    以下是一个可重复的示例 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")
      )
    
    
    

    enter image description here

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

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