簡體   English   中英

matplotlib:不同比例的疊加圖?

[英]matplotlib: overlay plots with different scales?

到目前為止,我有以下代碼:

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)

使用每個軸的autoscale_on=True選項,我認為每個圖都應該有自己的 y 軸限制,但看起來它們都共享相同的值(即使它們共享不同的軸)。 如何將它們設置為縮放以顯示每個datamatrix[:,i] (只是對.set_ylim()的顯式調用?)而且,如何為第三個變量( datamatrix[:,2] ) 上面可能需要? 謝謝大家。

聽起來你想要的是子圖......你現在所做的沒有多大意義(或者我對你的代碼片段感到非常困惑,無論如何......)。

嘗試更像這樣的事情:

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()

在此處輸入圖片說明

編輯:

如果你不想要子圖,你的代碼片段更有意義。

您正試圖在彼此的頂部添加三個軸。 Matplotlib 認識到在圖形上已經有一個精確大小和位置的子圖,因此它每次都返回相同的軸對象。 換句話說,如果您查看列表ax ,您會發現它們都是同一個 object

如果您真的想這樣做,則每次添加軸時都需要將fig._seen重置為空字典。 但是,您可能並不真的想這樣做。

與其將三個獨立的圖放在一起, twinx看看使用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()

在此處輸入圖片說明

使用@joe-kington 的回答快速引導一些東西來繪制共享一個 x 軸的多個 y 軸:在此處輸入圖片說明

# 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()

感謝 Joe Kington 的回答,我可以為我的要求提出一個解決方案,即所有額外的 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()

在此處輸入圖片說明

twinx 簡短示例:

fig1 = matplotlib.figure.Figure()  # Make a figure
ax1 = fig1.add_subplot()           # Add the primary axis
ax1.plot([100, 300, 200])          # Plot something
ax2 = ax1.twinx()                  # Add the secondary axis
ax2.plot([5000, 2000, 6000])       # Plot something with a different scale
display( fig1 )                    # Display it (Jupyter only)

在此處輸入圖片說明

我使用了這段代碼,它成功地生成了兩個 Y 軸(主要和次要),它們具有從 Excel 文件讀取數據的所需比例:

X = df[['x-axis variable']]
Y1=df[['1st Y-Variable']]
Y2=df[['2nd Y-Variable']]
Y3=df[['3rd Y-Variable']]

fig, ax1 = plt.subplots(figsize=(10,6))
ax2 = ax1.twinx()

ax1.plot(X, Y1, 'g', label='Curve.1 name') #plotting on primary Y-axis
ax1.plot(X, Y2, 'm', label='Curve.2 name') #plotting on primary Y-axis

ax2.plot(X, wob, 'b', label='Curve.3 name') #plotting on **second** Y-axis

ax1.set_ylim(0, 350) #Define limit/scale for primary Y-axis
ax2.set_ylim(1000, 1300) #Define limit/scale for secondary Y-axis

plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM