【问题标题】:How to label max value points in a faceted plot in R?如何在R中的多面图中标记最大值点?
【发布时间】:2018-01-19 23:52:07
【问题描述】:

我读到有人有类似的问题 (ggplot2 and facet_grid : add highest value for each plot),但我仍然无法解决我的问题。

以此为例:

data.frame(x=rnorm(100),y=rnorm(100),z=rep(c("A","B"))) %>% ggplot(aes(x,y)) + geom_point() + facet_wrap(~z)

我只想标记每个图中的最大 y 值点。我想使用+ geom_label_repel(aes(label=y)),但我最终标记了所有点。

我也尝试使用+ geom_label(data=.[.$y==max(.$y),], aes(label=y)),我认为. 应该是placeholder for the argument left of the pipe operator,但这样做是行不通的。

古怪的注释:我也想在不将数据框分配给全局环境中的变量的情况下执行此操作,因此我使用了管道运算符。我们可以在不分配任何变量的情况下做到这一点吗?

【问题讨论】:

    标签: r plot ggplot2 label


    【解决方案1】:

    您可以通过过滤原始数据集并将其作为“数据”参数传递给您的文本几何图形来做到这一点。看起来有点奇怪(而且你必须使用“.”运算符来引用 dplyr 链的数据集,我个人不喜欢这个),但它确实有效,而且你不必从外部引用数据。

    set.seed(1222)
    
    data.frame(x=rnorm(100),y=rnorm(100),z=rep(c("A","B"))) %>% 
      ggplot(aes(x,y)) + geom_point() + 
      geom_label(data = . %>% group_by(z) %>% filter(y == max(y)), aes(label = sprintf('%0.2f', y)), hjust = -0.5) +
      facet_wrap(~z)
    

    【讨论】:

      【解决方案2】:

      如果你不想要ggplot里面的管道,上面的代码可以修改如下:

      set.seed(1222)
      data.frame(x=rnorm(100),y=rnorm(100),z=rep(c("A","B"))) %>% 
      group_by(z) %>% 
      mutate(labelthis = ifelse(y==max(y), format(y, digits = 2, scientific = T), NA)) %>%
          ggplot(aes(x,y)) + 
          geom_point() + 
          ggrepel::geom_label_repel(aes(label = labelthis), min.segment.length = 0) +
          facet_wrap(~z)
      

      【讨论】:

        猜你喜欢
        • 2021-08-16
        • 1970-01-01
        • 2013-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-26
        • 1970-01-01
        • 2021-03-29
        相关资源
        最近更新 更多