2016-03-19 6 views
1

2つの値のセットが線形に依存しています。したがって、適切なスケールで2番目のy軸を持つ単一のグラフが必要です。Matplotlib.pyplot:既存のプロットの2番目のy軸を設定する方法

これを行うにはどのような方法が最適ですか?ちょうど2つのバープロットを作る

は私に、オーバーラップを与える:

import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(4) 
y2 = np.array([23, 32, 24, 28]) 
y1 = 4.2 * y2 

fig = plt.figure(1, figsize=(6,6)) 

ax = fig.add_subplot(111) 
ax.bar(x, y2) 
ax.set_ylabel('Consumption in $m^3$') 
ax2 = ax.twinx() 
ax2.bar(x, y1, alpha=0.5) 
ax2.set_ylabel('Consumption in EUR') 

plt.savefig('watercomsumption.png', format='png', bbox_inches="tight") 

example-plot

おかげでたくさん!


:-) EDIT

私が不明確だったかもしれません。私は単一グラフを作りたいと思います。 次のようなものです。しかし、bar-functionを2回呼び出してalpha=0で隠すよりもエレガントな方法がありますか?

import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(4) 
y2 = np.array([23, 32, 24, 28]) 
y1 = 4.2 * y2 

y2max = np.max(y2) * 1.1 

fig = plt.figure(1, figsize=(6,6)) 

ax = fig.add_subplot(111) 
ax.bar(x, y2) 
ax.set_ylabel('Consumption in $m^3$') 
ax2 = ax.twinx() 

ax2.bar(x, y1, alpha=0) 
ax2.set_ylabel('Consumption in EUR') 

ax.set_ylim(ymax=y2max) 
ax2.set_ylim(ymax=4.2*y2max) 

plt.savefig('watercomsumption.png', format='png', bbox_inches="tight") 

example-code2

答えて

5

あなたが変換を提供するために、第2のY軸を望ん二回だけbarを呼び出すにしたくない場合は、単純にすべての2回目のバーを呼び出すことはありません。 2番目のY軸を作成して調整することはできますが、は実際に何も描画しません。

import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(4) 
y2 = np.array([23, 32, 24, 28]) 
y1 = 4.2 * y2 

y2max = np.max(y2) * 1.1 

fig = plt.figure(1, figsize=(6,6)) 

ax = fig.add_subplot(111) 
ax.bar(x, y2) 
ax.set_ylabel('Consumption in $m^3$') 
ax2 = ax.twinx() 

ax2.set_ylabel('Consumption in EUR') 

ax.set_ylim(ymax=y2max) 
ax2.set_ylim(ymax=4.2*y2max) 

enter image description here

+0

努力のためにありがとうございましたが、これは私が探していたものではありません。私は私の質問ではっきりしていないかもしれませんが、私はバー機能を2度呼び出さずに方法を探しています。私は上記の他の例を加えました!再び、ありがとう! – smoneck

+0

@smoneck第2部で更新されました。単に「bar」と呼ぶのではなく、ylimsを変更するだけです。 – Suever

+0

質問を定性的に変更することは非常に残念ですが、とにかくヒントに感謝します。あなたが気づいていないのはいつも最も明白です。真ん中の冷蔵庫には何が入っていますか? :-) – smoneck

関連する問題