簡體   English   中英

使用ggplot2繪制樣條函數

[英]Plotting a spline function with ggplot2

我想用ggplot2繪制樣條函數。 我用這個時:

library(ggplot2)

spline_x <- 1:6
spline_y <- c(0, 0.5, 2, 2, 0.5, 0)
spl_fun <- splinefun(spline_x, spline_y)

p <- ggplot()
p + stat_function(fun = spl_fun) + xlim(min(spline_x), max(spline_x)) + ylim(min(spline_y), max(spline_y))

我得到一個空的情節。 plot()的作用相同:

plot(spl_fun,
     xlim = c(min(spline_x), max(spline_x)),
     ylim = c(min(spline_y) - 1, max(spline_y) + 1)
    )

另外,如何在多行上使用stat_function拆分行? 如果我只是輸入換行符(比如plot()示例),它(當然)在調用stat_function后停止stat_function ,並且不再考慮x / ylim。

你沒有給ggplot任何東西使用,也沒有傳遞給函數的值。 嘗試:

library(ggplot2)

spline_x <- 1:6
spline_y <- c(0, 0.5, 2, 2, 0.5, 0)
spl_fun <- splinefun(spline_x, spline_y)

p <- ggplot(data.frame(x=spline_x, y=spline_y), aes(x, y))
p <- p + stat_function(fun = spl_fun)
p

在此輸入圖像描述

p <- p + xlim(min(spline_x), max(spline_x))
p <- p + ylim(min(spline_y), max(spline_y))
p

在此輸入圖像描述

在即將要發布的新GGPLOT2(通過devtools安裝),可以使用geom_xspline在我的(也即將要發布的) ggalt具有包geom_xspline功能(這將產生類似的結果取決於參數):

library(ggplot2) # devtools::install_github("hadley/ggplot2")
library(ggalt)   # devtools::install_github("hrbrmstr/ggplot2")

spline_x <- 1:6
spline_y <- c(0, 0.5, 2, 2, 0.5, 0)

p <- ggplot(data.frame(x=spline_x, y=spline_y), aes(x, y))
p <- p + geom_xspline(spline_shape=1)
p

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM