简体   繁体   English

子集数据时如何将 geom_repel_text 与 geom_jitter 点对齐?

[英]How to align geom_repel_text to geom_jitter points when subsetting the data?

I am making boxplots and jitter to show each individual point.我正在制作箱线图和抖动来显示每个单独的点。 I am then putting text labels on each point.然后我在每个点上放置文本标签。 This works fine but as soon as I try to subset which points I want label, the text doesn't align any longer.这工作正常,但是一旦我尝试对我想要标签的点进行子集化,文本就不再对齐了。

Here is my code (with some help from this page): Aligning geom_text to geom_jitter points这是我的代码(在此页面有一些帮助): Aligning geom_text to geom_jitter points

library(ggplot2)
ggplot(mtcars, aes(vs, wt, group = am, label = wt)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(position = position_jitter(seed = 1)) +
  geom_text_repel(data = subset(mtcars, wt > 3),
                  position = position_jitter(seed = 1))

Here is my plot.这是我的情节。 As you can see the labels are not aligned with the points.如您所见,标签未与点对齐。 带有抖动和子集标签的箱线图

Any ideas why this doesn't work?任何想法为什么这不起作用?

The issue is that by subsetting ggrepel will only see this part of your data and assumes that your are only plotting the subset.问题是,通过子集设置ggrepel只会看到这部分数据,并假设您只是在绘制子集。 If you want ggrepel to take account of all your data use an ifelse condition to select the points you want to label instead of subsetting:如果您希望ggrepel考虑所有数据,请使用ifelse条件来选择要标记的点而不是子集:

library(ggplot2)
library(ggrepel)
ggplot(mtcars, aes(vs, wt, group = am, label = wt)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(position = position_jitter(seed = 1)) +
  geom_text_repel(aes(label = ifelse(wt > 3, wt, "")), position = position_jitter(seed = 1))

An alternative is to use a custom alpha to make the weights you don't want to display invisible:另一种方法是使用自定义 alpha 使您不想显示的权重不可见:

library(ggplot2)

ggplot(within(mtcars, visible <- wt > 3),
       aes(vs, wt, group = am, label = wt)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(position = position_jitter(seed = 1)) +
  geom_text_repel(position = position_jitter(seed = 1),
                  aes(alpha = visible)) +
  scale_alpha_manual(values = c(0, 1)) +
  guides(alpha = guide_none())

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM