图左侧有两个y轴

时间:2013-11-22 13:58:47

标签: matplotlib

我想绘制具有不同y轴的曲线,它们共享相同的x轴。我之前使用过twinx函数,但它将它们绘制在图的不同侧面。有没有办法在左侧绘制它们。我正在寻找类似以下enter image description here

的内容

但是两个轴都在同一侧。上面示例的代码是here

在不同的情况下,可以按特定顺序绘制曲线,因为z顺序不适用于twinx

2 个答案:

答案 0 :(得分:17)

以红色显示的是默认的twinx()行为。 example中的额外修改适用于绿色显示的内容。

您可以修改两个类似于green的新轴,但选择left脊椎并应用负偏移。所以添加/更改示例:

par1.spines["left"].set_position(("axes", -0.4)) # red one
par2.spines["left"].set_position(("axes", -0.2)) # green one

make_patch_spines_invisible(par1)
make_patch_spines_invisible(par2)

par1.spines["left"].set_visible(True)
par1.yaxis.set_label_position('left')
par1.yaxis.set_ticks_position('left')

par2.spines["left"].set_visible(True)
par2.yaxis.set_label_position('left')
par2.yaxis.set_ticks_position('left')

enter image description here

来自线条的zorder仅在轴内被考虑(或者它出现?),因为你有相互独立的轴,你应该修改轴的zorder

host.set_zorder(1)
par1.set_zorder(2)
par2.set_zorder(3)

请注意,host有一个白色背景,将其置于顶部将隐藏其他行,除非您将背景设置为透明。

答案 1 :(得分:1)

这里有一个功能,可以在有人需要时自动在任何一侧进行制作。

import matplotlib.pyplot as plt
import numpy as np

def plotting_several_axis(variables, positions, colors, ylabels, xlabel, yaxislabels, 
                          fontsize=12, y_axis_dist = 0.2, figsize=(7,5)):
    """
    plotting_several_axis(variables, positions, colors, ylabels, xlabel, yaxislabels, 
                          fontsize=12, y_axis_dist = 0.2, figsize=(7,5))

    Example:

    a1 = np.arange(1, 100, 1)
    a2 = np.arange(1, 100, 1)
    a = [a1, a2]
    b = [i**2 for i in a]
    c = [i/5 for i in b]
    d = [i*8 for i in c]
    e = [i+5 for i in d]
    variables = [a, b, c, d, e]

    positions = ['right', 'left', 'right', 'left', 'right']
    colors = ['green', 'blue', 'red', 'magenta', 'brown']
    ylabels = ['potatoes', 'rice', 'tomatoes', 'juice', 'cotton']
    xlabel = 'price'
    yaxislabels = ['item', 'kg', 'bunch', 'Liters', 'cm3']

    """
    def make_patch_spines_invisible(ax):
        ax.set_frame_on(True)
        ax.patch.set_visible(False)
        for sp in ax.spines.values():
            sp.set_visible(False)


    fig, host = plt.subplots(figsize=figsize)
    fig.subplots_adjust(right=0.75)


    ###### HOST PLOTTING
    tkw = dict(size=4, width=1.5, labelsize=fontsize)


    p1, = host.plot(variables[0][0], variables[0][1], colors[0], label=ylabels[0])
    host.set_xlabel(xlabel, fontsize=fontsize)
    host.set_ylabel(yaxislabels[0], fontsize=fontsize)
    host.yaxis.label.set_color(p1.get_color())
    host.tick_params(axis='y', colors=p1.get_color(), **tkw)
    host.tick_params(axis='x', **tkw)
    # host.set_xlim(0, 2)

    lines = [p1]

#     y_axis_dist = 0.2
    inc_r = 1
    inc_l = -y_axis_dist

    for ix, i in enumerate(variables):


        if ix != 0:
            par = host.twinx()
            if positions[ix] == 'right':
                par.spines[positions[ix]].set_position(("axes", inc_r))
                inc_r += y_axis_dist
            elif positions[ix] == 'left':
                par.spines[positions[ix]].set_position(("axes", inc_l))
                inc_l -= y_axis_dist

            make_patch_spines_invisible(par)
            par.spines[positions[ix]].set_visible(True)
            par.yaxis.set_label_position(positions[ix])
            par.yaxis.set_ticks_position(positions[ix])
            p, = par.plot(variables[ix][0], variables[ix][1], colors[ix], label=ylabels[ix])
            par.set_ylabel(yaxislabels[ix], fontsize=fontsize)
            par.yaxis.label.set_color(p.get_color())
            par.tick_params(axis='y', colors=p.get_color(), **tkw)
            lines.append(p)

    host.legend(lines, [l.get_label() for l in lines], fontsize=fontsize, loc='lower right')
    plt.savefig("example.png", dpi=300, bbox_inches="tight")

    plt.show()

a1 = np.arange(1, 100, 1)
a2 = np.arange(1, 100, 1)
a = [a1, a2]
b = [i**2 for i in a]
c = [i/5 for i in b]
d = [i*8 for i in c]
e = [i+5 for i in d]
variables = [a, b, c, d, e]

positions = ['right', 'left', 'right', 'left', 'right']
colors = ['green', 'blue', 'red', 'magenta', 'brown']
ylabels = ['potatoes', 'rice', 'tomatoes', 'juice', 'cotton']
xlabel = 'price'
yaxislabels = ['item', 'kg', 'bunch', 'Liters', 'cm3']

plotting_several_axis(variables, positions, colors, ylabels, xlabel, yaxislabels, y_axis_dist=0.2)

Example