如何在R中的多面图中标注最大值点? [英] How to label max value points in a faceted plot in R?

查看:126
本文介绍了如何在R中的多面图中标注最大值点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到有人有类似的问题( ggplot2和facet_grid:为每个图添加最高值),但我仍然无法解决我的问题.

I read someone had a similar question (ggplot2 and facet_grid : add highest value for each plot) but I still couldn't solve my problem.

以这个为例:

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)),但最终标记了所有点.

I want to label only the max y-value point in each plot. I wanted to use + geom_label_repel(aes(label=y)) but I ended up labelling all points.

我还尝试了+ geom_label(data=.[.$y==max(.$y),], aes(label=y)),我认为.应该是

I also tried with + geom_label(data=.[.$y==max(.$y),], aes(label=y)) where I thought . should be a placeholder for the argument left of the pipe operator but doing it this way does not work.

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

Quirky note: I also want to do this without assigning the data frame to a variable in the global environment so I'm using the pipe operator. Can we do this without assigning any variables?

推荐答案

您可以通过过滤原始数据集并将其作为"data"参数传递给文本geom来实现.看起来有些奇怪(并且您必须使用."运算符来引用dplyr链的数据集,我个人并不喜欢),但是它确实有效,并且您不必从外部引用数据.

You can do this by filtering your original data set and passing that as the "data" argument to your text geom. It looks a little strange (and you have to use the "." operator to reference the dplyr chain's data set, which I personally don't like), but it definitely works, and you don't have to externally reference the data.

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)

这篇关于如何在R中的多面图中标注最大值点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆