R ggplot:仅将标签应用于绘图中的最后N个数据点

我在R中创建了一个折线图(图表),每个数据点都有标签.由于数据点数量众多,因此标签的图形变得非常完整.我想仅为最后N个(比如4个)数据点应用标签.我已经在geom_label_repel函数中尝试了子集和尾部但是无法将它们视为我们或得到错误消息.我的数据集由99个值组成,分布在3组(KPI)上.

我在R中有以下代码:

library(ggplot)
library(ggrepel)

data.trend <- read.csv(file=....)

plot.line <- ggplot(data=data.trend, aes(x = Version, y = Value, group = KPI, color = KPI)) +

  geom_line(aes(group = KPI), size = 1) +
  geom_point(size = 2.5) +


  # Labels defined here
  geom_label_repel(
    aes(Version, Value, fill = factor(KPI), label = sprintf('%0.1f%%', Value)),
    box.padding = unit(0.35, "lines"),
    point.padding = unit(0.4, "lines"),
    segment.color = 'grey50',
    show.legend = FALSE
  )

);

我很公平,我对R很新.也许我想念一些基本的东西.

提前致谢.

最佳答案
最简单的方法是将geom_label_repel中的data =参数设置为仅包含要标记的点.

这是一个可重复的例子:

set.seed(1235)
data.trend <- data.frame(Version = rnorm(25), Value = rnorm(25), 
                         group = sample(1:2,25,T), 
                         KPI = sample(1:2,25,T))

ggplot(data=data.trend, aes(x = Version, y = Value, group = KPI, color = KPI)) +
  geom_line(aes(group = KPI), size = 1) +
  geom_point(size = 2.5) +
  geom_label_repel(aes(Version, Value, fill = factor(KPI), label = sprintf('%0.1f%%', Value)),
    data = tail(data.trend, 4),                 
    box.padding = unit(0.35, "lines"),
    point.padding = unit(0.4, "lines"),
    segment.color = 'grey50',
    show.legend = FALSE)

enter image description here

不幸的是,这与排斥算法略有混淆,使得标签放置相对于未标记的其他点不是最理想的(您可以在上图中看到某些点被标签覆盖).

因此,更好的方法是使用颜色和填充来简单地使不需要的标签不可见(通过为要隐藏的标签设置颜色和填充为NA):

ggplot(data=data.trend, aes(x = Version, y = Value, group = KPI, color = KPI)) +
  geom_line(aes(group = KPI), size = 1) +
  geom_point(size = 2.5) +
  geom_label_repel(aes(Version, Value, fill = factor(KPI), label = sprintf('%0.1f%%', Value)),
                   box.padding = unit(0.35, "lines"),
                   point.padding = unit(0.4, "lines"),
                   show.legend = FALSE,
                   color = c(rep(NA,21), rep('grey50',4)),
                   fill = c(rep(NA,21), rep('lightblue',4)))

enter image description here

转载注明原文:R ggplot:仅将标签应用于绘图中的最后N个数据点 - 代码日志