我有一些這樣的代碼:
seq(0, 2*pi, length.out = 100) %>%
cbind.data.frame(t = ., Y = sin(.)) %>%
qplot(t, Y, data = ., geom = "line")
geom_segment(aes(y = mean(Y), yend = max(Y), x = , xend = ))
我想創建一個geom_segment引數x并xend取其最高值t的地方。Y我發現了描述如何根據另一個變數的最大值找到一個變數的值的問題,但是,我不知道如何應用該解決方案以便它可以在ggplot呼叫中使用,而無需保存物件到環境。任何幫助將不勝感激,謝謝。
uj5u.com熱心網友回復:
使用which.max,就像在問題鏈接到的帖子中一樣,找到第一個最大值Y并提取相應的t值。我還添加了水平軸。
suppressPackageStartupMessages({
library(ggplot2)
library(dplyr)
})
seq(0, 2*pi, length.out = 100) %>%
data.frame(t = ., Y = sin(.)) %>%
ggplot(aes(t, Y))
geom_line()
geom_segment(aes(y = mean(Y), yend = max(Y),
x = t[which.max(Y)], xend = t[which.max(Y)]))
geom_hline(yintercept = 0)

由reprex 包創建于 2022-05-07 (v2.0.1)
uj5u.com熱心網友回復:
我不確定,因為輸出很奇怪,但試試這個:
seq(0, 2*pi, length.out = 100) %>%
cbind.data.frame(t = ., Y = sin(.)) %>%
qplot(t, Y, data = ., geom = "line")
geom_segment(aes(y = mean(Y),
yend = which(Y == max(Y)),
x = which(Y == max(Y)) ,
xend = which(Y == max(Y))))
uj5u.com熱心網友回復:
或者(重新)計算aes“實時”主題,您可以對 的資料框執行相同的操作geom。根據資料操作的程度,這在某些情況下很方便:
seq(0, 2*pi, length.out = 100) %>%
cbind.data.frame(t = ., Y = sin(.)) %>%
qplot(t, Y, data = ., geom = "line")
geom_segment(data = . %>%
mutate(mean_Y = mean(Y)) %>%
arrange(Y) %>% ## sort, so that row w highest Y comes last
tail(1), ## keep last row (with highest Y)
aes(y = mean_Y, yend = Y,
x = t, xend = t)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471573.html
上一篇:用circlize繪制
