简体   繁体   English

R ggrepel:隐藏一些标签

[英]R ggrepel: hiding some labels

Hi I been getting Aesthetics error when trying to only display labels for certain subsets. 嗨,我一直在尝试仅显示某些子集的标签时出现美学错误。 For example. 例如。

library("ggplot2")
library(gplots)
library(ggrepel)

set.seed(10)
data <- data.frame(label=letters[1:21], number= runif(21, min=0, max=100))
data$label <-factor(data$label)

ggplot(data, aes(x=label, y=number, fill=data$label )) +
geom_bar(stat="identity") +
geom_text_repel(data=  data[data$number > 80,], aes(label =data$label ), 
                  arrow = arrow(length = unit(0.01, 'npc')), box.padding = unit(1.5, 'lines'),color="black"   )

When I do this I get the following error 当我这样做时,出现以下错误

Error: Aesthetics must be either length 1 or the same as the data (2): label, x, y, fill

even if I replace the label with a vector such as c("label1","label2") I still get an error. 即使我将标签替换为c("label1","label2")类的向量c("label1","label2")我仍然会收到错误消息。

I'm doing something wrong but I can't figure it out. 我做错了,但我无法解决。 The only way I can do this is to create a separate vector with the same length and use that as the label, however I think there is a way to subset directly. 我可以做到这一点的唯一方法是创建一个具有相同长度的单独矢量并将其用作标签,但是我认为有一种直接子集的方法。 thanks! 谢谢!

Change the code to: 将代码更改为:

ggplot(data, aes(x=label, y=number, fill=data$label )) +
geom_bar(stat="identity") +
geom_text_repel(data=  data[data$number > 80,], aes(label =label ), ##<- Change here
                  arrow = arrow(length = unit(0.01, 'npc')), box.padding = unit(1.5, 'lines'),color="black"   )

The problem is that in the call to aes within geom_text_repel() you use data$label , a column within the 21 row dataframe, whereas you want label to be evaluated within the 2 row subset of the data. 问题在于,在geom_text_repel()aes的调用中,您使用data$label ,它位于21行数据geom_text_repel()一列,而您希望在数据的2行子集内对label求值。

In this case, you've obscured the problem by calling your data data , it might be more straightforward to spot the error if you'd called it something more meaningful. 在这种情况下,您通过调用数据data掩盖了问题,如果您将其称为更有意义的话,发现错误可能会更直接。

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

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