在ggplot中标记特定点

时间:2019-08-23 13:14:59

标签: r ggplot2

我正在尝试根据特定条件(值> 0.4)为ggplot中的点分配标签,但我希望根据团队名称应用点的颜色。我可以为所有数据点做颜色和标签(看起来确实很乱),但是努力应用标签标准。

尝试复制此示例,但不允许按团队为点着色:

Label points in geom_point

Plot <- ggplot(data = df, aes(x=Prem$Expected.Goals.p90..exl.pens., y=Prem$Expected.Assists.p90, color=Prem$Team, label=Prem$Player)) + 
geom_point() +
geom_abline(intercept = 0, linetype = 2, colour = "darkblue") + 
scale_x_continuous(name = "Non-penalty Expected Goals per 90", limits = c(0, 0.7)) +
scale_y_continuous(name = "Expected Assists per 90", limits = c(0, 0.7)) + 
theme_bw() +
scale_colour_manual(values = c("firebrick1", "green", "navy", "darksalmon", "brown4", "darkgreen", "dodgerblue", "yellow", "orange", "blue", "black", "lightblue")) 


Plot + geom_label_repel(aes(label = (Prem$Player)),

              box.padding   = 0.35, 
              point.padding = 0.5,
              segment.color = 'grey50')


df1 <- subset(df, Prem$Expected.Goals.p90..exl.pens. > 0.4)

Plot + geom_label_repel(data = df1,    aes(x=df1$Expected.Goals.p90..exl.pens., y=df1$Expected.Assists.p90, label=df1$Player),
size = 5,
box.padding = unit(0.35, "lines"),
point.padding = unit(0.3, "lines")

曾经尝试创建一个子集df1来解决此问题,但是我收到以下错误消息:

  

错误:美学的长度必须为1或与数据(8)相同:   x,y,标签,颜色

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

geom_text_repel的帮助页面中,可以通过在标签列中添加“”而不是文本来省略标签:

p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars), colour = factor(cyl))) +
geom_point()

mtcars$label <- rownames(mtcars)
mtcars$label[1:15] <- ""
p + geom_text_repel(data = mtcars, aes(wt, mpg, label = label))

很难想象没有可重现的数据该怎么办,但是对于您而言,我认为您要做的就是创建一个标签列,并在您的Expected.Goals.p90..exl.pens.列的行中添加“”高于0.4:

Prem$label <- Prem$Player
Prem[Prem$Expected.Goals.p90..exl.pens. > 0.4, "label"] <- ""

# ... Create 'Plot' object, and add:

Plot + geom_label_repel(aes(label = label))