我在 R 中繪制了一個類似于下面的圖。除了這些值的平均值之外,我還繪制了一些值。我想圍繞平均值兩側連續 5 次的值繪制一個矩形。我很難做到這一點,任何見解將不勝感激。
編輯:我應該澄清一下,我正在嘗試自動完成此操作,我不想手動設定矩形的坐標。
可重現的例子
library(ggplot2)
mydata <- data.frame(
id = c(1:20),
result = c(102,99,102,99,102, rep.int(105,5), 102,99,102,99,102, rep.int(95,5))
)
mymean <- 100
ggplot(mydata, aes(x = id, y = result))
geom_point()
geom_hline(yintercept = mymean)
當前情節:

想要的劇情:

uj5u.com熱心網友回復:
您首先需要一種演算法來遍歷資料并根據您的標準將其分類為不同的組(其中最難的部分)。然后,您可以獲取結果并用于geom_rect()將矩形添加到圖表中。classify_data()下面的函式進行分類,矩形加上geom_rect(). 如果您有落在平均分,你不希望他們組中的矩形,你可以添加一個條件,以測驗該。
classify_groups <- function(df, id_col = "id", val_col = "result") {
id <- df[[id_col]]
values <- df[[val_col]]
current_ids <- c()
current_values <- c()
result <- data.frame(id = numeric(),
xmin = numeric(),
xmax = numeric(),
y = numeric())
for (i in 1:(length(id))) {
if (length(current_values) == 0 | values[i] %in% current_values) {
current_values <- c(current_values, values[i])
current_ids <- c(current_ids, id[i])
} else {
current_ids <- c(id[i])
current_values <- c(values[i])
}
if (length(current_values) == 5) {
result <- result %>%
add_row(id = i,
xmin = min(current_ids),
xmax = max(current_ids),
y = max(current_values))
current_ids <-c()
current_values <- c()
}
}
result
}
mydata <- data.frame(
id = c(1:20),
result = c(102,99,102,99,102, rep.int(105,5), 102,99,102,99,102, rep.int(95,5))
)
mymean = 100
groups <- classify_groups(mydata)
ggplot(mydata, aes(x = id, y = result))
geom_point()
geom_hline(yintercept = mymean)
geom_rect(data = groups,
aes(xmin = xmin - 0.5,
xmax = xmax 0.5,
ymin = y - 0.5,
ymax = y 0.5,
group = id),
alpha = 0,
color = 'darkorange',
size=1,
inherit.aes = FALSE)
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371928.html
上一篇:在R中,如何使抖動(geom_jitter())留在其對應的箱線圖中而不延伸到相鄰的箱線圖中?
下一篇:在ggplot中為點添加垂直線
