2017-02-26 74 views
-2

我正在使用matplotlib twinx繪製同一軸上的多個變量。但我有一個問題,爲此我找不到解決方案。爲了簡單起見,我附上了下面的代碼繪製的小代碼和圖形。
在這幅圖中,我需要將這些條顯示在軸的底部,如圖2所示。但在圖2中,ax1t的yticks保持不變。我也需要將它們顯示在底部。我怎樣才能做到這一點?不同尺度的Matplotlib twinx

代碼:

import matplotlib.pyplot as plt 
import numpy as np 

fig, ax1 = plt.subplots() 
ax1.plot([4, 2, 8, 6, 4, 7, 3, 5]) 
ax1t = ax1.twinx() 
ax1t.bar(np.arange(8), [45, 42, 55, 36, 58, 45, 48, 62], alpha=0.4) 
plt.show() 

enter image description here

圖片2 enter image description here

+0

您想爲每個欄添加標籤值嗎? – Serenity

+0

目前還不清楚你的意思是「在軸線底部顯示的條形圖及其y標記標記」*。請花更多的想法來描述問題。你得到了什麼,它有多遠,不符合你的期望。相應地編輯你的問題。 – ImportanceOfBeingErnest

+0

好吧,我正在編輯.. –

回答

3

我想這是你想要的 -

import matplotlib.pyplot as plt 
import numpy as np 

fig, ax1 = plt.subplots() 
ax1.plot([4, 2, 8, 6, 4, 7, 3, 5]) 
ax1t = ax1.twinx() 

ax1t.bar(np.arange(8), [45, 42, 55, 36, 58, 45, 48, 62], alpha=0.4) 
ax1t.set_ylim([10,500]) 
ax1t.set_yticks([10, 50, 90]) 
plt.show() 

更改Y軸的比例使用set_ylim然後明確地傳遞在y蜱使用set_yticks。您可以根據您的方便隨意調整參數。

enter image description here

+0

是的。謝謝! –

+0

一個奇怪的圖形,確實 – Crispin

+0

@ hashcode55 upvote顯然已經理解了完全不清楚和令人困惑的問題。 – ImportanceOfBeingErnest

1

from matplotlib examples

import matplotlib.pyplot as plt 
import numpy as np 


f, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=True) 
ax1.plot([4, 2, 8, 6, 4, 7, 3, 5]) 
ax2.bar(np.arange(8), [45, 42, 55, 36, 58, 45, 48, 62], alpha=0.4) 

# Fine-tune figure; make subplots close to each other and hide x ticks for 
# all but bottom plot. 
f.subplots_adjust(hspace=0) 
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False) 

plt.show() 

enter image description here

+0

您創建了另一個子圖來執行此操作。但是,我需要將它們繪製在同一個軸上。 –

+0

如果您希望它們位於同一軸上,那麼向下推動條的唯一方法是修改y軸比例。你爲什麼不能把它們放在不同的子圖上? – Crispin