Python matplotlib 繪制雙Y軸曲線圖的示例代碼
更新時間:2020年06月12日 14:25:33 作者:松鼠愛出餅干
Matplotlib是非常強大的python畫圖工具,這篇文章主要介紹了Python matplotlib 繪制雙Y軸曲線圖,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
Matplotlib簡介
Matplotlib是非常強大的python畫圖工具
Matplotlib可以畫圖線圖、散點圖、等高線圖、條形圖、柱形圖、3D圖形、圖形動畫等。
Matplotlib安裝
pip3 install matplotlib#python3
雙X軸的
可以理解為共享y軸
ax1=ax.twiny() ax1=plt.twiny()
雙Y軸的
可以理解為共享x軸
ax1=ax.twinx() ax1=plt.twinx()
自動生成一個例子
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 function
ax2.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()

例子:畫了一個雙y軸坐標的圖表
# -*- coding: utf-8 -*-
#調用包
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#讀取文件
io=r'E:\工作\專項\白騎士數據驗證\白騎士數據匯總表.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() #畫網格
x=total.index-1
#為什么+1,因為對不齊,所以使用時根據情況編寫
y=total['var1']
ax.plot(x,y,'k--o',alpha=0.5) #畫折線圖
ax.set_xlim([0,16])
#設置x軸的取值范圍 這個可以讓x軸與y軸的起點一致
ax.set_xticks(np.arange(0,16)) #設置x軸的刻度范圍
ax.set_xticklabels(np.arange(0,16),rotation=30)
#設置x軸上的刻度
ax.set_ylim([0,1800]) #同理y軸數值范圍
ax.set_yticks(range(0,1800,300))#設置y軸的刻度范圍
ax.set_yticklabels(range(0,1800,300))#設置y軸上的刻度
ax.legend(loc='upper left') #設置ax子圖的圖例(legend)
#新知識點
for a,b in zip(x,y): #設置注釋 zip函數是對應關系
ax.text(a,b,b,ha='center',va='bottom',fontsize=15)
#重點
ax1=ax.twinx()
#這個是能夠實現雙y軸的重點,共享x軸;還有一種是雙x軸的圖表換成ax.twiny()
y1=total[['adopt','reject']]
y1.plot.bar(ax=ax1,alpha=0.5)
#這個是matplotlib中條形圖的繪制方法,如果使用seaborn繪制方法使用sns.barplot()函數,需要調整很多細節(jié)
#這里只設置了y軸的刻度,x軸的刻度設置了一下偶爾會出現失敗,值得注意的是要將數據對齊
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)成習慣這個最好寫一下#
#保存圖片
plt.savefig('path') #圖表輸出到本地
結果顯示:

總結
到此這篇關于Python matplotlib 繪制雙Y軸曲線圖的文章就介紹到這了,更多相關Python matplotlib 曲線圖內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
- python 如何在 Matplotlib 中繪制垂直線
- python matplotlib擬合直線的實現
- Python實現在matplotlib中兩個坐標軸之間畫一條直線光標的方法
- Python+matplotlib實現簡單曲線的繪制
- Python matplotlib繪制圖形實例(包括點,曲線,注釋和箭頭)
- 教你利用python的matplotlib(pyplot)繪制折線圖和柱狀圖
- Python?matplotlib實現折線圖的繪制
- python數據可視化之matplotlib.pyplot基礎以及折線圖
- python學習之使用Matplotlib畫實時的動態(tài)折線圖的示例代碼
- python??Matplotlib繪圖直線,折線,曲線
相關文章
解決import tensorflow導致jupyter內核死亡的問題
這篇文章主要介紹了解決import tensorflow導致jupyter內核死亡的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02

