欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python?matplotlib用面積填充實(shí)現(xiàn)lmplot的代碼示例

 更新時(shí)間:2023年07月18日 10:23:15   作者:微小冷  
這篇文章主要介紹了python?matplotlib如何用面積填充實(shí)現(xiàn)lmplot,文章通過(guò)代碼示例介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴可以參考閱讀

示例

在繪圖時(shí)經(jīng)常遇到類(lèi)似區(qū)域填充的問(wèn)題,比如對(duì)于y = sin ? x y=\sin xy=sinx函數(shù),想填充其與X軸所圍成的區(qū)間,那么就可以使用fill_between函數(shù)。

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 2, 0.01)
y = np.sin(2 * np.pi * x)
plt.plot(x, y, color='black')
plt.fill_between(x, y)
plt.grid()
plt.show()

效果如下

參數(shù)

fill_between參數(shù)如下,其中x, y1, y2都是數(shù)組,表示希望覆蓋的范圍,具體邏輯是,對(duì)于某點(diǎn)xi?,將對(duì)應(yīng)的[y1i?,y2i?]范圍內(nèi)涂上顏色。在上面的示例中,只設(shè)置了xy1,而y2默認(rèn)為0,所以繪制的就是y1到0范圍內(nèi)的值。

fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, *,**kwargs)

其他參數(shù)含義如下

  • where 可以指定參與繪圖的范圍,一般是一個(gè)布爾型數(shù)組
  • interpolate 為True時(shí)采用插值
  • step 可選’pre’, ‘post’, ‘mid’,表示步進(jìn)方案
plt.plot(x, y, color='black')
plt.fill_between(x, y, where=y > 0, facecolor='green', alpha=.5)
plt.fill_between(x, y, where=y < 0, facecolor='red', alpha=.5)
plt.show()

結(jié)果如圖

回歸圖

有了這種填充工具,就可以做出類(lèi)似seaborn中的lmplot,這種圖形在數(shù)據(jù)擬合時(shí)十分有用,可以在除了擬合線(xiàn)之外,再將數(shù)據(jù)的分布范圍標(biāo)出。

首先創(chuàng)造一組帶有誤差的y = 2x + 1y=2x+1y=2x+1數(shù)據(jù),并通過(guò)最小二乘法得到其擬合參數(shù)。

x = np.arange(0, 2, 0.02)
err = np.random.rand(100)/2
y = 2*x + 1 + err
# 構(gòu)造并調(diào)用最小二乘法
A = np.array([x, np.ones_like(x)]).T
kb, res, _, _ = np.linalg.lstsq(A, y)

下面就對(duì)擬合結(jié)果進(jìn)行繪制,首先根據(jù)擬合出來(lái)的k , bk, bk,b,來(lái)得到趨勢(shì)線(xiàn)Y = kx + bY=kx+bY=kx+b,然后調(diào)用繪圖函數(shù),對(duì)原始數(shù)據(jù)、趨勢(shì)線(xiàn)、分布區(qū)間進(jìn)行繪制

Y = kb[0]*x + kb[1]
dx = (x-x.mean())**2
E = x.std() * np.sqrt(1/len(x) + dx / np.sum(dx))
plt.scatter(x, y, marker='.')   # 原始數(shù)據(jù)
plt.plot(x, Y)                  # 趨勢(shì)線(xiàn)
plt.fill_between(x, Y - E, Y + E, alpha=0.5)
plt.show()

效果如下

到此這篇關(guān)于python matplotlib用面積填充實(shí)現(xiàn)lmplot的代碼示例的文章就介紹到這了,更多相關(guān)python matplotlib實(shí)現(xiàn)lmplot內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論