我有一个数据集,我想将特定的标签(在本例中是行名)添加到我的ggplot图中。然而,当我使用filter时,控制台上会显示一个关于数据帧长度的错误。
require("ggrepel") require("tidyerse") x <- sample(x = 1:20, size = 30, replace = T) y <- sample(x = 1:20, size = 30, replace = T) df <- data.frame(x,y) df %>% ggplot(aes(x=x,y=y))+ geom_point()+ geom_text_repel(aes(label = rownames(df))) df %>% ggplot(aes(x=x,y=y))+ geom_point()+ geom_text_repel(data = df %>% filter(x>10), aes(label = rownames(df)))
中出错 check_aesthetics() :
check_aesthetics()
df 对于行名,则仍将返回所有行名。因此,您还需要在 rownames() aes(label = rownames(df %>% filter(x > 10))) ).
df
rownames()
aes(label = rownames(df %>% filter(x > 10)))
library(tidyverse) df %>% ggplot(aes(x = x, y = y)) + geom_point() + geom_text_repel(data = df %>% filter(x > 10), aes(label = rownames(df %>% filter(x > 10))))
另一种方法可以是:
my_label 以x>10 不需要在ggplot内子集:
my_label
library(tidyverse) df %>% group_by(group_id = x > 10) %>% mutate(my_label = ifelse(group_id == TRUE, as.character(row_number()), "")) %>% ggplot(aes(x=x,y=y))+ geom_point()+ geom_text_repel(aes(label=my_label))