简体   繁体   English

如何在matplotlib中将次轴图布置在主轴图之下?

[英]How to arrange plots of secondary axis to be below plots of primary axis in matplotlib?

I am trying to plot two curves on two y-axes as shown in figure. 我正在尝试在两个y轴上绘制两条曲线,如图所示。 But the green plot (needle lift) is plotted above the primary axis plot even though I set zorder to be 1 and 2 for the red plot (pressure). 但是,即使我将红色曲线(压力)的zorder设置为1和2,绿色曲线(针升力)也会绘制在主轴曲线上方。

在此处输入图片说明

The code I used: 我使用的代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker as tick
data = np.genfromtxt("secondary_axis.dat", skiprows = 2, delimiter = ',')
time = data[:, 0]
pressure = data[:, 1] * 0.006894759086775369
pressure_charge = data[0, 0]
needle_lift = data[:, 2]
figure = plt.figure(figsize=(5.15, 5.15))
figure.clf()
plot = plt.subplot(111)
plot.plot(time, pressure, label = r'\textit{Raw}', zorder = 2)
plot.set_xlabel(r'\textit{X}', labelpad=6)
plot.set_ylabel(r'\textit{Y}', labelpad=6)
primary_ticks = len(plot.yaxis.get_major_ticks())
ax2 = plot.twinx()
ax2.plot(time, needle_lift, color='#4DAF4A', zorder = 1)
ax2.grid(False)
ax2.set_ylabel(r'\textit{Z}', labelpad=6)
ax2.yaxis.set_major_locator(tick.LinearLocator(primary_ticks))
plt.show()

And data is available here 而且数据可在这里

How to place the green (needle lift) plot below the red plot (pressure) with matplotlib? 如何使用matplotlib将绿色(针升)图放置在红色图(压力)下方?

Updated code with rc settings 使用rc设置更新了代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc_context
from matplotlib import ticker as tick


def init_plot_dark():
    params = {'backend' : 'agg', 'legend.numpoints' : 1,
    'lines.linewidth' : 1.0, 'lines.linestyle' : '-', 'axes.facecolor' : '#EEEEEE', 'axes.edgecolor' : '#FFFFFF',
    'axes.linewidth' : 0.0, 'axes.grid' : True, 'axes.titlesize' : 'large', 'axes.labelsize' : 12, 'axes.labelweight' : 'normal',
    'axes.labelcolor' : '000000', 'axes.axisbelow' : True, 'polaraxes.grid' : True , 'axes3d.grid' : True,
    'axes.color_cycle' : ('#E41A1C', '#377EB8', '#4DAF4A', '#984EA3', '#FF7F00', '#FFFF33', '#A65628', '#F781BF', '#999999'),
    'xtick.major.size' : 4 ,'xtick.minor.size' : 2 ,'xtick.major.width' : 0 ,'xtick.minor.width' : 0 ,'xtick.major.pad' : 6,
    'xtick.minor.pad' : 6, 'xtick.color' : '#000000' , 'xtick.labelsize' : 10, 'xtick.direction' : 'in',
    'ytick.major.size' : 4, 'ytick.minor.size' : 2 ,'ytick.major.width' : 0 ,'ytick.minor.width' : 0 ,'ytick.major.pad' : 6,
    'ytick.minor.pad' : 6 ,'ytick.color' : '#000000', 'ytick.labelsize' : 10, 'ytick.direction' : 'in',
    'grid.color' : '#FFFFFF', 'grid.linestyle' : '-', 'grid.linewidth' : 0.5, 'grid.alpha' : 1.0,
    'legend.fontsize' : 10, 'legend.borderaxespad' : 0.5, 'legend.shadow' : False, 'legend.frameon' : True}
    plt.rcParams.update(params)

init_plot_dark()

data = np.genfromtxt("secondary_axis.dat", skiprows = 2, delimiter = ',')
time = data[:, 0]
pressure = data[:, 1] * 0.006894759086775369
pressure_charge = data[0, 0]
needle_lift = data[:, 2]
figure = plt.figure(figsize=(5.15, 5.15))
figure.clf()
plot = plt.subplot(111)
plot.plot(time, pressure, label = r'\textit{Raw}', zorder = 2)
plot.set_xlabel(r'\textit{X}', labelpad=6)
plot.set_ylabel(r'\textit{Y}', labelpad=6)
primary_ticks = len(plot.yaxis.get_major_ticks())
ax2 = plot.twinx()
ax2.plot(time, needle_lift, color='#4DAF4A', zorder = 1)
ax2.grid(False)
ax2.set_ylabel(r'\textit{Z}', labelpad=6)
ax2.yaxis.set_major_locator(tick.LinearLocator(primary_ticks))
plt.show()

You need to set the zorder of your first axis to be above the zorder of your second axis, but you need to do it after plotting them both. 您需要将第一个轴的zorder设置为在第二个轴的zorder之上,但是您需要在将它们都绘制后再做。 Add these two lines just before your plt.show() 在您的plt.show()之前添加这两行

plot.set_zorder(ax2.get_zorder()+1)
plot.patch.set_visible(False)

The first line gets the zorder correct, but would hide the second axis comepletely. 第一行的zorder正确,但会完全隐藏第二条轴。 So, we also need to remove the canvas, using the second line. 因此,我们还需要使用第二行删除画布。

在此处输入图片说明

EDIT 编辑

To get the grid lines right using your rcParams , you could do the following instead: Switch which line is plotted on your plot axis and your ax2 axis (ie pressure on ax2 and needle lift on plot ), and then change around which side their axis and tick labels are: 要使用rcParams使网格线正确,可以改为执行以下操作:切换在plot轴和ax2轴上绘制哪条线(即ax2上的压力和plot上的针头提升),然后更改其轴的哪一侧和刻度标签是:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc_context
from matplotlib import ticker as tick


def init_plot_dark():
    params = {'backend' : 'agg', 'legend.numpoints' : 1,
    'lines.linewidth' : 1.0, 'lines.linestyle' : '-', 'axes.facecolor' : '#EEEEEE', 'axes.edgecolor' : '#FFFFFF',
    'axes.linewidth' : 0.0, 'axes.grid' : True, 'axes.titlesize' : 'large', 'axes.labelsize' : 12, 'axes.labelweight' : 'normal',
    'axes.labelcolor' : '000000', 'axes.axisbelow' : True, 'polaraxes.grid' : True , 'axes3d.grid' : True,
    'axes.color_cycle' : ('#E41A1C', '#377EB8', '#4DAF4A', '#984EA3', '#FF7F00', '#FFFF33', '#A65628', '#F781BF', '#999999'),
    'xtick.major.size' : 4 ,'xtick.minor.size' : 2 ,'xtick.major.width' : 0 ,'xtick.minor.width' : 0 ,'xtick.major.pad' : 6,
    'xtick.minor.pad' : 6, 'xtick.color' : '#000000' , 'xtick.labelsize' : 10, 'xtick.direction' : 'in',
    'ytick.major.size' : 4, 'ytick.minor.size' : 2 ,'ytick.major.width' : 0 ,'ytick.minor.width' : 0 ,'ytick.major.pad' : 6,
    'ytick.minor.pad' : 6 ,'ytick.color' : '#000000', 'ytick.labelsize' : 10, 'ytick.direction' : 'in',
    'grid.color' : '#FFFFFF', 'grid.linestyle' : '-', 'grid.linewidth' : 0.5, 'grid.alpha' : 1.0,
    'legend.fontsize' : 10, 'legend.borderaxespad' : 0.5, 'legend.shadow' : False, 'legend.frameon' : True}
    plt.rcParams.update(params)

init_plot_dark()

data = np.genfromtxt("secondary_axis.dat", skiprows = 2, delimiter = ',')
time = data[:, 0]
pressure = data[:, 1] * 0.006894759086775369
pressure_charge = data[0, 0]
needle_lift = data[:, 2]
figure = plt.figure(figsize=(5.15, 5.15))
figure.clf()
plot = plt.subplot(111)
plot.plot(time, needle_lift, color='#4DAF4A', zorder = 1)
plot.set_xlabel(r'\textit{X}', labelpad=6)
plot.set_ylabel(r'\textit{Z}', labelpad=6)
ax2 = plot.twinx()
ax2.plot(time, pressure, label = r'\textit{Raw}', zorder = 2)
ax2.grid(False)
ax2.set_ylabel(r'\textit{Y}', labelpad=6)
primary_ticks = len(ax2.yaxis.get_major_ticks())
plot.yaxis.set_major_locator(tick.LinearLocator(primary_ticks))

plot.yaxis.tick_right()
plot.yaxis.set_label_position("right")

ax2.yaxis.tick_left()
ax2.yaxis.set_label_position("left")

plt.show()

在此处输入图片说明

The answer above is correct, but I'd like to write a shorter and and simpler one. 上面的答案是正确的,但是我想写一个更短,更简单的答案。

Given: 鉴于:

fig, ax1 = plt.subplots()
ax2 = ax1.twiny()

Just add (somewhere, before or after the plotting): 只需添加(在绘图之前或之后的某个位置):

ax1.set_zorder(1)  # default zorder is 0 for ax1 and ax2
ax1.patch.set_visible(False)  # prevents ax1 from hiding ax2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM