我有以下資料(產品成本與時間),如下所示:
annum <- c(1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913,
1914, 1915, 1916, 1917, 1918, 1919)
cost <- c(0.0000, 18.6140, 92.1278, 101.9393, 112.0808, 122.5521,
133.3532, 144.4843, 244.5052, 275.6068, 295.2592, 317.3145,
339.6527, 362.3537, 377.7775, 402.8443, 437.5539)
mydata <- as.data.frame(cbind(annum, cost))
g <- ggplot(mydata, aes(x = annum, y = cost))
g <- g geom_point()
g <- g scale_y_continuous(labels=scales::dollar_format())
g

如果洗掉第一個資料點,將只有兩個段,但上面的代碼仍然有效。
mydata <- mydata[-(1:2), ]
n <- nrow(mydata)
segmts <- 2
h <- (segmts 1)/n
b <- breakpoints(cost ~ annum, h = h, breaks = segmts - 1L, data = mydata)
bp <- mydata[b$breakpoints, "annum"]
bp <- c(bp, Inf)
mydata$grp <- findInterval(mydata$annum, bp, left.open = TRUE)
mydata$grp <- factor(mydata$grp)
g geom_smooth(
mapping = aes(group = grp),
method = "lm",
formula = y ~ x,
se = FALSE
)

uj5u.com熱心網友回復:
這有幫助嗎。使用loess方法?
library(tidyverse)
ggplot(mydata, aes(x = annum, y = cost))
geom_point()
geom_smooth(method = "loess", formula = "y~x")

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/368707.html
上一篇:有沒有辦法以某種格式列印圖形?
