我有一個散點圖,我必須在上面顯示y 值的邊界。
geom_smooth表示平均值或中值,但我必須表示最大值和最小值。如何繪制綠線?

代碼:
library(ggplot2)
suaon <- mtcars
pla <- ggplot(data = suaon, mapping = aes(x = mpg, y = wt))
pla <- pla geom_point(mapping = aes(color = cyl), size = 1.4)
pla <- pla geom_smooth(span = 0.4, method = "loess", se = FALSE,color = "red", size = 0.8, alpha = 0.1)
pla <- pla labs(x = "MPG", y = "WT")
pla
uj5u.com熱心網友回復:
如果您正在尋找一個簡單的解決方案,那么您可以使用兩個for回圈。一種用于最大值,一種用于最小值。
我還沒有整理代碼,我相信有更好的方法,但這有效。
library(tidyverse)
library(ggplot2)
suaon <- mtcars
##arrange by wt so that the largest wt values are first in the data frame.
max_dat <- suaon %>% arrange(-wt) %>% mutate(max_val = F)
##loop through dataframe checking if the mpg value for i is greater than the current mpg value
##if it is, then include this point as a maximum value and update current_x to the mpg value for row i.
current_x = 0
for(i in 1:nrow(max_dat)){
if(max_dat$mpg[i] > current_x){
max_dat$max_val[i] <- T
current_x <- max_dat$mpg[i]
}
}
max_dat <- max_dat %>% filter(max_val == T)
min_dat <- suaon %>% arrange(mpg) %>% mutate(min_val = F)
current_min = max(min_dat$wt)
i <- 1
for(i in 1:nrow(dat)){
if(min_dat$wt[i] < current_min){
min_dat$min_val[i] <- T
current_min <- min_dat$wt[i]
}
}
min_dat <- min_dat %>% filter(min_val == T)
pla <- ggplot(data = suaon, mapping = aes(x = mpg, y = wt))
pla <- pla geom_point(mapping = aes(color = cyl), size = 1.4)
pla <- pla geom_smooth(span = 0.4, method = "loess", se = FALSE,color = "red", size = 0.8, alpha = 0.1)
pla <- pla labs(x = "MPG", y = "WT")
pla <- pla geom_line(data = max_dat, aes(x = mpg, y = wt))
pla <- pla geom_line(data = min_dat, aes(x = mpg, y = wt))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315915.html
