2011-10-11 9 views
37

は、これまでのところ、私は次のコードを持っている:場合でも(各軸のautoscale_on=Trueオプションでmatplotlib:異なるスケールのオーバーレイプロット?

colors = ('k','r','b') 
ax = [] 
for i in range(3): 
    ax.append(plt.axes()) 
    plt.plot(datamatrix[:,0],datamatrix[:,i],colors[i]+'o') 
    ax[i].set(autoscale_on=True) 

を、私は、各プロットは、独自のy軸の範囲を持っていなければならないと思ったが、彼らのすべてが同じ値を共有して表示されますそれらは異なる軸を共有する)。 datamatrix[:,i].set_ylim()への明示的な呼び出し)の範囲を表示するようにスケールを設定するにはどうしたらいいですか?また、上記の必要な第3変数(datamatrix[:,2])のオフセットy軸を作成するにはどうすればよいですか?皆さんありがとう。

答えて

94

サブプロットが欲しいと思うように聞こえます...あなたが今やっていることはあまり意味がありません(または、私はあなたのコードスニペットによって、まったく混乱しています...)。

import matplotlib.pyplot as plt 
import numpy as np 

fig, axes = plt.subplots(nrows=3) 

colors = ('k', 'r', 'b') 
for ax, color in zip(axes, colors): 
    data = np.random.random(1) * np.random.random(10) 
    ax.plot(data, marker='o', linestyle='none', color=color) 

plt.show() 

enter image description here

編集:

はもっとこのような何か試してみてください、あなたがサブプロットをしたくない場合は

を、あなたのコードスニペットは、多くの意味があります。

お互いの上に3つの軸を追加しようとしています。 Matplotlibは、図の正確なサイズと位置にサブプロットが既にあることを認識していますので、毎回同じのAxesオブジェクトを返しています。言い換えると、リストaxを見ると、それらはすべてという同じオブジェクトであることがわかります。

実際にとしたい場合は、軸を追加するたびにfig._seenを空のdictにリセットする必要があります。あなたはおそらくそれをやりたいとは思わないでしょう。

代わりに3つの独立したプロットを配置する代わりに、twinxを使用してみてください。

など。

import matplotlib.pyplot as plt 
import numpy as np 
# To make things reproducible... 
np.random.seed(1977) 

fig, ax = plt.subplots() 

# Twin the x-axis twice to make independent y-axes. 
axes = [ax, ax.twinx(), ax.twinx()] 

# Make some space on the right side for the extra y-axis. 
fig.subplots_adjust(right=0.75) 

# Move the last y-axis spine over to the right by 20% of the width of the axes 
axes[-1].spines['right'].set_position(('axes', 1.2)) 

# To make the border of the right-most axis visible, we need to turn the frame 
# on. This hides the other plots, however, so we need to turn its fill off. 
axes[-1].set_frame_on(True) 
axes[-1].patch.set_visible(False) 

# And finally we get to plot things... 
colors = ('Green', 'Red', 'Blue') 
for ax, color in zip(axes, colors): 
    data = np.random.random(1) * np.random.random(10) 
    ax.plot(data, marker='o', linestyle='none', color=color) 
    ax.set_ylabel('%s Thing' % color, color=color) 
    ax.tick_params(axis='y', colors=color) 
axes[0].set_xlabel('X-axis') 

plt.show() 

enter image description here

+0

おかげで - 実際に私はすべての点で単一のパネルをしたいけど、それぞれが異なるyスケールを持っています... – hatmatrix

+0

うまくいけば編集が助けてくれることを望みます。私はy軸に実際の範囲でラベルを付けることを前提としています。あなたがしない場合(そして、基本的にy値が無意味であることを望むなら)、これはずっと簡単に行うことができます。 –

+0

ああ、私が思っていたと思った属性です。しかし、手動で脊柱を調整することは、たとえスケールが正しく操作されているかぎり、データと必ずしも接続されていない「浮動」軸を使用していても、行く方法のようです。ありがとう。 – hatmatrix

7

ブートストラップ@joe-kington's答え使用して、x軸を共有する複数のy軸チャートへ速い何か: enter image description here

# d = Pandas Dataframe, 
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ] 
def chart(d,ys): 

    from itertools import cycle 
    fig, ax = plt.subplots() 

    axes = [ax] 
    for y in ys[1:]: 
     # Twin the x-axis twice to make independent y-axes. 
     axes.append(ax.twinx()) 

    extra_ys = len(axes[2:]) 

    # Make some space on the right side for the extra y-axes. 
    if extra_ys>0: 
     temp = 0.85 
     if extra_ys<=2: 
      temp = 0.75 
     elif extra_ys<=4: 
      temp = 0.6 
     if extra_ys>5: 
      print 'you are being ridiculous' 
     fig.subplots_adjust(right=temp) 
     right_additive = (0.98-temp)/float(extra_ys) 
    # Move the last y-axis spine over to the right by x% of the width of the axes 
    i = 1. 
    for ax in axes[2:]: 
     ax.spines['right'].set_position(('axes', 1.+right_additive*i)) 
     ax.set_frame_on(True) 
     ax.patch.set_visible(False) 
     ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter()) 
     i +=1. 
    # To make the border of the right-most axis visible, we need to turn the frame 
    # on. This hides the other plots, however, so we need to turn its fill off. 

    cols = [] 
    lines = [] 
    line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>', 
       '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_']) 
    colors = cycle(matplotlib.rcParams['axes.color_cycle']) 
    for ax,y in zip(axes,ys): 
     ls=line_styles.next() 
     if len(y)==1: 
      col = y[0] 
      cols.append(col) 
      color = colors.next() 
      lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color)) 
      ax.set_ylabel(col,color=color) 
      #ax.tick_params(axis='y', colors=color) 
      ax.spines['right'].set_color(color) 
     else: 
      for col in y: 
       color = colors.next() 
       lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color)) 
       cols.append(col) 
      ax.set_ylabel(', '.join(y)) 
      #ax.tick_params(axis='y') 
    axes[0].set_xlabel(d.index.name) 
    lns = lines[0] 
    for l in lines[1:]: 
     lns +=l 
    labs = [l.get_label() for l in lns] 
    axes[0].legend(lns, labs, loc=0) 

    plt.show() 
3

を私が出てくる可能性がジョーキングトンの答えのおかげですべての追加のy軸がグラフの左側にあることを私の要求のために解決してください。

それだけで周りの仕事だから、私はまだ、それが正しい行う方法を知りたいのです

import matplotlib.pyplot as plt 
import numpy as np 
# To make things reproducible... 
np.random.seed(1977) 

fig, ax = plt.subplots() 

# Twin the x-axis twice to make independent y-axes. 
axes = [ax, ax.twinx(), ax.twinx()] 

# Make some space on the right side for the extra y-axis. 
fig.subplots_adjust(right=0.75) 

# Move the last y-axis spine over to the right by 20% of the width of the axes 
axes[1].spines['right'].set_position(('axes', -0.25)) 
axes[2].spines['right'].set_position(('axes', -0.5)) 

# To make the border of the right-most axis visible, we need to turn the frame 
# on. This hides the other plots, however, so we need to turn its fill off. 
axes[-1].set_frame_on(True) 
axes[-1].patch.set_visible(False) 

# And finally we get to plot things... 
colors = ('Green', 'Red', 'Blue') 
intAxNo = 0 
for ax, color in zip(axes, colors): 
    intAxNo += 1 
    data = np.random.random(1) * np.random.random(10) 
    ax.plot(data, marker='o', linestyle='none', color=color) 
    if (intAxNo > 1): 
     if (intAxNo == 2): 
      ax.set_ylabel('%s Thing' % color, color=color, labelpad = -40) 
     elif (intAxNo == 3): 
      ax.set_ylabel('%s Thing' % color, color=color, labelpad = -45) 
     ax.get_yaxis().set_tick_params(direction='out') 
    else: 
     ax.set_ylabel('%s Thing' % color, color=color, labelpad = +0) 

    ax.tick_params(axis='y', colors=color) 
axes[0].set_xlabel('X-axis') 


plt.show() 

enter image description here

関連する問題