python畫曲線函數(shù) 用python畫函數(shù)曲線

Python matplotlib之函數(shù)圖像繪制、線條rc參數(shù)設(shè)置

為避免中文顯示出錯,需導(dǎo)入matplotlib.pylab庫

稱多網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)公司!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站開發(fā)等網(wǎng)站項目制作,到程序開發(fā),運(yùn)營維護(hù)。創(chuàng)新互聯(lián)公司公司2013年成立到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運(yùn)維經(jīng)驗,來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)公司。

1.2.1 確定數(shù)據(jù)

1.2.2 創(chuàng)建畫布

1.2.3 添加標(biāo)題

1.2.4 添加x,y軸名稱

1.2.5 添加x,y軸范圍

1.2.6 添加x,y軸刻度

1.2.7 繪制曲線、圖例, 并保存圖片

保存圖片時,dpi為清晰度,數(shù)值越高越清晰。請注意,函數(shù)結(jié)尾處,必須加plt.show(),不然圖像不顯示。

繪制流程與繪制不含子圖的圖像一致,只需注意一點:創(chuàng)建畫布。

合理調(diào)整figsize、dpi,可避免出現(xiàn)第一幅圖橫軸名稱與第二幅圖標(biāo)題相互遮蓋的現(xiàn)象.

2.2.1 rc參數(shù)類型

2.2.2 方法1:使用rcParams設(shè)置

2.2.3 方法2:plot內(nèi)設(shè)置

2.2.4 方法3:plot內(nèi)簡化設(shè)置

方法2中,線條形狀,linestyle可簡寫為ls;線條寬度,linewidth可簡寫為lw;線條顏色,color可簡寫為c,等等。

不能直接寫出函數(shù)的表達(dá)式 怎么在python里畫函數(shù)圖象呢?

不寫出y=f(x)這樣的表達(dá)式,由隱函數(shù)的等式直接繪制圖像,以x2+y2+xy=1的圖像為例,使用sympy間接調(diào)用matplotlib工具的代碼和該二次曲線圖像如下(注意python里的乘冪符號是**而不是^,還有,python的sympy工具箱的等式不是a==b,而是a-b或者Eq(a,b),這幾點和matlab的區(qū)別很大)

直接在命令提示行的里面運(yùn)行代碼的效果

from sympy import *;

x,y=symbols('x y');

plotting.plot_implicit(x**2+y**2+x*y-1);

python之KS曲線

# 自定義繪制ks曲線的函數(shù)

def plot_ks(y_test, y_score, positive_flag):

# 對y_test,y_score重新設(shè)置索引

y_test.index = np.arange(len(y_test))

#y_score.index = np.arange(len(y_score))

# 構(gòu)建目標(biāo)數(shù)據(jù)集

target_data = pd.DataFrame({'y_test':y_test, 'y_score':y_score})

# 按y_score降序排列

target_data.sort_values(by = 'y_score', ascending = False, inplace = True)

# 自定義分位點

cuts = np.arange(0.1,1,0.1)

# 計算各分位點對應(yīng)的Score值

index = len(target_data.y_score)*cuts

scores = target_data.y_score.iloc[index.astype('int')]

# 根據(jù)不同的Score值,計算Sensitivity和Specificity

Sensitivity = []

Specificity = []

for score in scores:

? ? # 正例覆蓋樣本數(shù)量與實際正例樣本量

? ? positive_recall = target_data.loc[(target_data.y_test == positive_flag) (target_data.y_scorescore),:].shape[0]

? ? positive = sum(target_data.y_test == positive_flag)

? ? # 負(fù)例覆蓋樣本數(shù)量與實際負(fù)例樣本量

? ? negative_recall = target_data.loc[(target_data.y_test != positive_flag) (target_data.y_score=score),:].shape[0]

? ? negative = sum(target_data.y_test != positive_flag)

? ? Sensitivity.append(positive_recall/positive)

? ? Specificity.append(negative_recall/negative)

# 構(gòu)建繪圖數(shù)據(jù)

plot_data = pd.DataFrame({'cuts':cuts,'y1':1-np.array(Specificity),'y2':np.array(Sensitivity),

? ? ? ? ? ? ? ? ? ? ? ? ? 'ks':np.array(Sensitivity)-(1-np.array(Specificity))})

# 尋找Sensitivity和1-Specificity之差的最大值索引

max_ks_index = np.argmax(plot_data.ks)

plt.plot([0]+cuts.tolist()+[1], [0]+plot_data.y1.tolist()+[1], label = '1-Specificity')

plt.plot([0]+cuts.tolist()+[1], [0]+plot_data.y2.tolist()+[1], label = 'Sensitivity')

# 添加參考線

plt.vlines(plot_data.cuts[max_ks_index], ymin = plot_data.y1[max_ks_index],

? ? ? ? ? ymax = plot_data.y2[max_ks_index], linestyles = '--')

# 添加文本信息

plt.text(x = plot_data.cuts[max_ks_index]+0.01,

? ? ? ? y = plot_data.y1[max_ks_index]+plot_data.ks[max_ks_index]/2,

? ? ? ? s = 'KS= %.2f' %plot_data.ks[max_ks_index])

# 顯示圖例

plt.legend()

# 顯示圖形

plt.show()

# 調(diào)用自定義函數(shù),繪制K-S曲線

plot_ks(y_test = y_test, y_score = y_score, positive_flag = 1)

Python如何畫函數(shù)的曲線

輸入以下代碼導(dǎo)入我們用到的函數(shù)庫。

import numpy as np

import matplotlib.pyplot as plt

x=np.arange(0,5,0.1);

y=np.sin(x);

plt.plot(x,y)

采用剛才代碼后有可能無法顯示下圖,然后在輸入以下代碼就可以了:

plt.show()

python 怎么畫與其他方法進(jìn)行比較的ROC曲線?

使用sklearn的一系列方法后可以很方便的繪制處ROC曲線,這里簡單實現(xiàn)以下。

主要是利用混淆矩陣中的知識作為繪制的數(shù)據(jù)(如果不是很懂可以先看看這里的基礎(chǔ)):

tpr(Ture Positive Rate):真陽率 圖像的縱坐標(biāo)

fpr(False Positive Rate):陽率(偽陽率) 圖像的橫坐標(biāo)

mean_tpr:累計真陽率求平均值

mean_fpr:累計陽率求平均值

import numpy as np

import matplotlib.pyplot as plt

from sklearn import svm, datasets

from sklearn.metrics import roc_curve, auc

from sklearn.model_selection import StratifiedKFold

iris = datasets.load_iris()

X = iris.data

y = iris.target

X, y = X[y != 2], y[y != 2] # 去掉了label為2,label只能二分,才可以。

n_samples, n_features = X.shape

# 增加噪聲特征

random_state = np.random.RandomState(0)

X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]

cv = StratifiedKFold(n_splits=6) #導(dǎo)入該模型,后面將數(shù)據(jù)劃分6份

classifier = svm.SVC(kernel='linear', probability=True,random_state=random_state) # SVC模型 可以換作AdaBoost模型試試

# 畫平均ROC曲線的兩個參數(shù)

mean_tpr = 0.0 # 用來記錄畫平均ROC曲線的信息

mean_fpr = np.linspace(0, 1, 100)

cnt = 0

for i, (train, test) in enumerate(cv.split(X,y)): #利用模型劃分?jǐn)?shù)據(jù)集和目標(biāo)變量 為一一對應(yīng)的下標(biāo)

cnt +=1

probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test]) # 訓(xùn)練模型后預(yù)測每條樣本得到兩種結(jié)果的概率

fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1]) # 該函數(shù)得到偽正例、真正例、閾值,這里只使用前兩個

mean_tpr += np.interp(mean_fpr, fpr, tpr) # 插值函數(shù) interp(x坐標(biāo),每次x增加距離,y坐標(biāo)) 累計每次循環(huán)的總值后面求平均值

mean_tpr[0] = 0.0 # 將第一個真正例=0 以0為起點

roc_auc = auc(fpr, tpr) # 求auc面積

plt.plot(fpr, tpr, lw=1, label='ROC fold {0:.2f} (area = {1:.2f})'.format(i, roc_auc)) # 畫出當(dāng)前分割數(shù)據(jù)的ROC曲線

plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') # 畫對角線

mean_tpr /= cnt # 求數(shù)組的平均值

mean_tpr[-1] = 1.0 # 坐標(biāo)最后一個點為(1,1) 以1為終點

mean_auc = auc(mean_fpr, mean_tpr)

plt.plot(mean_fpr, mean_tpr, 'k--',label='Mean ROC (area = {0:.2f})'.format(mean_auc), lw=2)

plt.xlim([-0.05, 1.05]) # 設(shè)置x、y軸的上下限,設(shè)置寬一點,以免和邊緣重合,可以更好的觀察圖像的整體

plt.ylim([-0.05, 1.05])

plt.xlabel('False Positive Rate')

plt.ylabel('True Positive Rate') # 可以使用中文,但需要導(dǎo)入一些庫即字體

plt.title('Receiver operating characteristic example')

plt.legend(loc="lower right")

plt.show()

本文標(biāo)題:python畫曲線函數(shù) 用python畫函數(shù)曲線
文章起源:http://muchs.cn/article24/dosdjje.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營銷推廣、靜態(tài)網(wǎng)站、微信公眾號、網(wǎng)站內(nèi)鏈、網(wǎng)站營銷企業(yè)網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁設(shè)計