如何在R中的刻面图中标记最大值点?

时间:2018-01-19 23:52:07

标签: r plot ggplot2 label

我读过某人有类似的问题(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)

faceted plot with randomized points

我想只标记每个图中的最大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,但这样做是行不通的。

古怪的说明:我还想在没有将数据框分配给全局环境中的变量的情况下这样做,所以我使用的是管道运算符。我们可以在不指定任何变量的情况下这样做吗?

2 个答案:

答案 0 :(得分:2)

您可以通过过滤原始数据集并将其作为“数据”参数传递给文本geom来完成此操作。它看起来有点奇怪(你必须使用“。”运算符来引用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)

enter image description here

答案 1 :(得分:0)

如果您不想在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)