2017-03-09 678 views
0

我有使用matplotlib一個使用twinx()函數來顯示具有不同的y值的兩個不同曲線的圖表:的Python - 增加了雙x軸matplotlib圖形尺寸

plt.plot(Current_Time[1000:66000],Avg_Duration[1000:66000],color='blue',label="Average Duration of All Parked Cars") 
#plt.figure(figsize=(10,10)) 
plt.legend(loc='upper left') 
plt.ylim(0,50000) 
plt.ylabel('Duration in Seconds') 
plt.xticks(rotation=90) 
plt2=plt.twinx() 
#plt2.figure(figsize=(10,10)) 
plt2.plot(Current_Time[1000:66000],Quantity[1000:66000],color='purple',label='Quantity of Cars Parked') 
plt2.set_ylabel('Cars Parked') 
plt2.legend(loc='upper right') 
plt.show() 

我遇到的問題是當我嘗試增加繪圖大小,它將圖表分開。有沒有辦法增加圖的大小,而不是分成兩個圖表?

+1

非重複性的代碼,沒有圖片,有什麼你期望在這裏?在演出前嘗試'''plt.tight_layout()'''。 – sascha

+0

@sascha,這段代碼很容易重現。 Current_Time,Avg_Duration和Quantity的任何隨機值列表都已足夠。我已經搜索了matplotlib文檔無濟於事。想知道是否有一種方法可以在增加尺寸時保持兩個圖表的覆蓋? –

+1

SO上的可重複性:複製問題代碼,運行,觀察。肯定不在這裏工作。當然,不同的數據看起來不同,隨機列表可以是任何東西,至少有一些不同的分佈,其中一些與其他分佈非常不同。 – sascha

回答

1

確實有可能在任何尺寸的圖中創建雙軸。一個人必須確保瞭解代碼的寫作。即請勿使用figure創建新數字,然後抱怨顯示第二個數字。

堅持到matplotlib狀態機接口,一個解決辦法是這樣的:

import matplotlib.pyplot as plt 
import numpy as np 

#get data 
x=np.arange(40) 
y=np.random.rand(len(x))*20000+30000 
y2=np.random.rand(len(x))*0.5 
#create a figure 
plt.figure(figsize=(10,10)) 
#plot to first axes 
plt.plot(x,y,color='blue',label="label1") 
plt.ylim(0,50000) 
plt.ylabel('ylabel1') 
plt.xticks(rotation=90) 
#create twin axes 
ax2=plt.gca().twinx() 
#plot to twin axes 
plt.plot(x,y2,color='purple',label='label2') 
plt.ylabel('ylabel2') 
plt.legend(loc='upper right') 
plt.show() 

或者,如果你喜歡的matplotlib API:

import matplotlib.pyplot as plt 
import numpy as np 

#get data 
x=np.arange(40) 
y=np.random.rand(len(x))*20000+30000 
y2=np.random.rand(len(x))*0.5 
#create a figure 
fig = plt.figure(figsize=(10,10)) 
ax = fig.add_subplot(111) 
#plot to first axes 
ax.plot(x,y,color='blue',label="label1") 
ax.set_ylim(0,50000) 
ax.set_ylabel('ylabel1') 
ax.set_xticklabels(ax.get_xticklabels(),rotation=90) 
#create twin axes 
ax2=ax.twinx() 
#plot to twin axes 
ax2.plot(x,y2,color='purple',label='label2') 
ax2.set_ylabel('ylabel2') 

h1, l1 = ax.get_legend_handles_labels() 
h2, l2 = ax2.get_legend_handles_labels() 
ax.legend(handles=h1+h2, labels=l1+l2, loc='upper right') 
plt.show()