Python matplotlib 繪制雙Y軸曲線圖的示例代碼
Matplotlib簡(jiǎn)介
Matplotlib是非常強(qiáng)大的python畫(huà)圖工具M(jìn)atplotlib可以畫(huà)圖線圖、散點(diǎn)圖、等高線圖、條形圖、柱形圖、3D圖形、圖形動(dòng)畫(huà)等。
Matplotlib安裝
pip3 install matplotlib#python3
雙X軸的可以理解為共享y軸
ax1=ax.twiny()ax1=plt.twiny()
雙Y軸的可以理解為共享x軸
ax1=ax.twinx()ax1=plt.twinx()
自動(dòng)生成一個(gè)例子
x = np.arange(0., np.e, 0.01)y1 = np.exp(-x)y2 = np.log(x)fig = plt.figure()ax1 = fig.add_subplot(111)ax1.plot(x, y1)ax1.set_ylabel(’Y values for exp(-x)’)ax1.set_title('Double Y axis')ax2 = ax1.twinx() # this is the important functionax2.plot(x, y2, ’r’)ax2.set_xlim([0, np.e])ax2.set_ylabel(’Y values for ln(x)’)ax2.set_xlabel(’Same X for both exp(-x) and ln(x)’)plt.show()
例子:畫(huà)了一個(gè)雙y軸坐標(biāo)的圖表
# -*- coding: utf-8 -*-#調(diào)用包import pandas as pd import numpy as np import matplotlib.pyplot as plt#讀取文件io=r’E:工作專項(xiàng)白騎士數(shù)據(jù)驗(yàn)證白騎士數(shù)據(jù)匯總表.xlsx’yinka=pd.read_excel(io,sheet_name=’YINKA_sample’)bqs=pd.read_excel(io,sheet_name=’BQS_result’)yinka_bqs=pd.merge(yinka,bqs,left_on=’no’,right_on=’no’,how=’inner’)#繪圖fig,ax=plt.subplots(1,1,figsize=(20, 300))ax.grid() #畫(huà)網(wǎng)格x=total.index-1 #為什么+1,因?yàn)閷?duì)不齊,所以使用時(shí)根據(jù)情況編寫(xiě)y=total[’var1’]ax.plot(x,y,’k--o’,alpha=0.5) #畫(huà)折線圖ax.set_xlim([0,16]) #設(shè)置x軸的取值范圍 這個(gè)可以讓x軸與y軸的起點(diǎn)一致ax.set_xticks(np.arange(0,16)) #設(shè)置x軸的刻度范圍ax.set_xticklabels(np.arange(0,16),rotation=30) #設(shè)置x軸上的刻度ax.set_ylim([0,1800]) #同理y軸數(shù)值范圍ax.set_yticks(range(0,1800,300))#設(shè)置y軸的刻度范圍ax.set_yticklabels(range(0,1800,300))#設(shè)置y軸上的刻度ax.legend(loc=’upper left’) #設(shè)置ax子圖的圖例(legend)#新知識(shí)點(diǎn)for a,b in zip(x,y): #設(shè)置注釋 zip函數(shù)是對(duì)應(yīng)關(guān)系 ax.text(a,b,b,ha=’center’,va=’bottom’,fontsize=15)#重點(diǎn)ax1=ax.twinx() #這個(gè)是能夠?qū)崿F(xiàn)雙y軸的重點(diǎn),共享x軸;還有一種是雙x軸的圖表?yè)Q成ax.twiny()y1=total[[’adopt’,’reject’]]y1.plot.bar(ax=ax1,alpha=0.5) #這個(gè)是matplotlib中條形圖的繪制方法,如果使用seaborn繪制方法使用sns.barplot()函數(shù),需要調(diào)整很多細(xì)節(jié)#這里只設(shè)置了y軸的刻度,x軸的刻度設(shè)置了一下偶爾會(huì)出現(xiàn)失敗,值得注意的是要將數(shù)據(jù)對(duì)齊ax1.set_ylim([0,1800])ax1.set_yticks(range(0,1800,300))ax1.set_yticklabels(range(0,1800,300))for e,f,w in zip(data_.index,data_[0],data_[1]): ax1.text(e-1,f,f,ha=’center’,va=’bottom’,fontsize=10,color=’b’) ax1.text(e-1,w,w,ha=’center’,va=’bottom’,fontsize=10,color=’g’)ax1.legend(loc=’best’)plt.show() #養(yǎng)成習(xí)慣這個(gè)最好寫(xiě)一下##保存圖片plt.savefig(’path’) #圖表輸出到本地
結(jié)果顯示:
總結(jié)
到此這篇關(guān)于Python matplotlib 繪制雙Y軸曲線圖的文章就介紹到這了,更多相關(guān)Python matplotlib 曲線圖內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP實(shí)現(xiàn)加法驗(yàn)證碼2. CSS可以做的幾個(gè)令你嘆為觀止的實(shí)例分享3. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)4. PHP循環(huán)與分支知識(shí)點(diǎn)梳理5. PHP session反序列化漏洞超詳細(xì)講解6. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))7. ASP基礎(chǔ)入門(mén)第二篇(ASP基礎(chǔ)知識(shí))8. Spring注入Date類型的三種方法總結(jié)9. ASP基礎(chǔ)知識(shí)Command對(duì)象講解10. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享
