如何在下面的代碼段中的多線圖上進行樣條平滑?附圖顯示了此代碼生成的兩個圖。
謝謝!
library(tidyverse)
library(ggplot2)
# group by cyl
by_cyl <- mtcars %>% group_by(cyl) %>% summarize(mpg = mean(mpg))
# group by cyl & gear
by_cyl_gear <- mtcars %>% group_by(cyl, gear) %>% summarize(mpg = mean(mpg))
# spline smoothing for a single line plot
spline_d <- as.data.frame(spline(by_cyl$cyl, by_cyl$mpg))
ggplot(data = by_cyl, aes(x = cyl, y = mpg))
geom_line(data = spline_d, aes(x = x, y = y))
geom_point()
ggtitle("Unpartitioned (smooth)")
# multi-line plot - how to do spline-smoothing here?
by_cyl_gear$gear <- as.character(by_cyl_gear$gear)
ggplot(data = by_cyl_gear, aes(x = cyl, y = mpg))
geom_line(aes(color = gear))
geom_point(aes(color = gear))
ggtitle("Partitioned by gear (non-smooth)")
theme(legend.position = c(0.9, 0.6))

uj5u.com熱心網友回復:
基本上它與單行相同。您可以split通過gear, 用于lapply計算每個拆分的樣條,然后使用例如bind_rows:
library(dplyr)
library(ggplot2)
# group by cyl & gear
by_cyl_gear <- mtcars %>%
group_by(cyl, gear) %>%
summarize(mpg = mean(mpg)) %>%
mutate(gear = as.character(gear))
#> `summarise()` has grouped output by 'cyl'. You can override using the `.groups` argument.
# split, lapply, bind_rows
spline_d <- by_cyl_gear %>%
split(.$gear) %>%
lapply(function(x) as.data.frame(spline(x$cyl, x$mpg))) %>%
bind_rows(.id = "gear")
ggplot(data = by_cyl_gear, aes(x = cyl, y = mpg, color = gear))
geom_line(data = spline_d, aes(x = x, y = y))
geom_point()
ggtitle("Partitioned by gear (non-smooth)")
theme(legend.position = c(0.9, 0.6))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/381226.html
上一篇:縱向資料框的呈現,按年份計數
