【问题标题】:How to mark a max/min point in geom smooth如何在几何平滑中标记最大/最小点
【发布时间】:2021-03-04 09:09:25
【问题描述】:

是否有一个函数可以让我突出显示几何平滑图上的 y 最大值?

我已经尝试过使用 ggHighlight,但我无法让它解决这个问题。

【问题讨论】:

  • 如果您提供具有预期输出的可重现示例,社区会更容易帮助您。所以每个人都可以测试他们的想法,看看哪一个可能是答案。以下是有关可重现示例的一些信息:stackoverflow.com/questions/5963269/…

标签: r ggplot2 max


【解决方案1】:

您可以获取图层数据以获取 ggplot 计算的值并过滤极值。

library(ggplot2)

# Generate some dummy data
x <- seq(0, 2 * pi, length.out = 100)
df <- data.frame(
  x = x,
  y = sin(x) + rnorm(length(x), sd = 0.2)
)

# Make plot
g <- ggplot(df, aes(x, y)) +
  geom_smooth()

# Get and filter extrema
ld <- layer_data(g)
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
ld <- ld[c(which.max(ld$y), which.min(ld$y)), ]

# Make an annotation
g + geom_segment(
  data = ld,
  aes(x = x, y = y, xend = x, yend = c(Inf, -Inf)),
  arrow = arrow(ends = "first")
)
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

【讨论】:

    猜你喜欢
    • 2019-03-19
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多