利用 R 繪製擬合曲線

Table of Contents

  1. 利用 R 繪製擬合曲線
    1. 單純使用 goemsmooth
    2. 單純使用 spline
    3. 同時使用前兩種方法

利用 R 繪製擬合曲線

我的主要使用 ggplot2 進行繪圖,這裏也只介紹 ggplot2 的相關方法。ide

利用 R 繪製擬合曲線主要有兩類方法:spa

  1. 利用 geomsmooth 進行曲線的擬合(method 選擇 loess 或者添加 formula);
  2. 利用 spline 進行插值操做,而後用 geomline 進行鏈接。

可是,這兩種方法都有一些缺陷。利用 geomsmooth 進行曲線的擬合在某些數據的狀況下會擬合比較差,甚至呈現折線。利用 spline 進行插值操做後繪圖會致使曲線必須通過實際值對應的點,致使曲線僵硬。在某些狀況下,兩種方法都沒法獲得咱們須要的圖形。3d

在本文中,須要繪製以下數據的圖形:code

density ROS
0 3.43
0.001 1.86
0.01 56.00
0.1 225.31
1 183.56
10 339.40
100 272.89
1000 204.17
10000 2.29

該數據表現了樣品隨着濃度的變化,觀測值變化的狀況。orm

單純使用 goem_smooth

library(ggplot2)
    ros <- read.csv('tem.csv', colClasses = c('character', 'numeric'))
    ggplot(ros, aes(x=density, y=ROS)) +
      geom_point() +
      geom_smooth(aes(x=density2, y=ROS), se = F, method = 'loess')

單純使用 spline

ros <- transform.data.frame(ros, density2=1:9)
    tem <- as.data.frame(spline(ros$density2, ros$ROS, n=10000))
    ggplot(ros, aes(x=density, y=ROS)) +
      geom_point() +
      geom_line(data = tem, aes(x=x, y=y))

同時使用前兩種方法

tem2 <- as.data.frame(spline(ros$density2, ros$ROS, n=100))
    ggplot(ros, aes(x=density, y=ROS)) +
      geom_point() +
      geom_smooth(data = tem2, aes(x=x, y=y), se = F, method = 'loess')

相關文章
相關標籤/搜索