matplotlib两个Y轴混合Z轴 [英] matplotlib two y axes with mixed z order

查看:63
本文介绍了matplotlib两个Y轴混合Z轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在两个y轴上绘制数据,以使第二个y轴上的某些数据位于第一个y轴图的后面,而其中的一部分在上面.基本上我想使用全局" zorder 参数.这可能吗?

I would like to plot data on two y axes such that some of the data on the second y axis is behind the first y axis graph and part of it is above. Essentially I would like to have use "global" zorder parameter. Is that possible?

这是一个最小的例子:

import numpy as np
import matplotlib.pyplot as plt

# generate data
x = np.linspace(0,30,30)
y1 = np.random.random(30)+x
y2 = np.random.random(30)+x*2

# create figure
fig, ax = plt.subplots()

# y1 axis
ax.plot(x,y1,lw=5,c='#006000', zorder=2)
ax.set_ylim((0,30))
ax.set_xlim((0,30))

# y2 axis
ax2 = ax.twinx()  # instantiate a second axes that shares the same x-axis
ax2.fill_between([0, 30], [10, 10], color='pink', lw=0, zorder=1)
ax2.fill_between([0, 30], [60, 60], y2=[10, 10], color='gray', lw=0, zorder=1)
ax2.plot(x, y2,'o',ms=3,c='black', zorder=3)
ax2.set_ylim((0,60))
ax2.set_xlim((0,30))

# move y1 axis to the front
ax.set_zorder(ax2.get_zorder()+1)
ax.patch.set_visible(False)

我希望背景填充颜色位于背景中,但黑色数据点应位于绿线之上.我试图通过为这些曲线定义zorder参数来实现此目的,但是显然zorder仅在一个轴内定义,而不是在多个轴上定义.

I would like the background fill color to be in the background but the black data points should be on top of the green line. I tried to achieve this by defining the zorder parameter for these curves but apparently the zorder is only defined within one axis and not across multiple axes.

推荐答案

这里有一个解决方案,可以满足您的需求,无论它在实施中可能是多么不理想.

Here is a solution that gets what you want, however sub-ideal it may be in implementation.

import numpy as np
import matplotlib.pyplot as plt

# generate data
x = np.linspace(0,30,30)
y1 = np.random.random(30)+x
y2 = np.random.random(30)+x*2

# create figure
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = ax2.twiny()
ax1.get_shared_x_axes().join(ax2, ax3)

# line
ax1.plot(x,y1,lw=5,c='#006000')
ax1.set_ylim((0,30))
ax1.set_xlim((0,30))

# points
ax2.plot(x, y2,'o',ms=3,c='black')
ax2.set_ylim((0,60))

# fills
ax3.set_xticklabels([])
ax3.get_xaxis().set_visible(False)
ax3.fill_between([0, 30], [10, 10], color='pink', lw=0)
ax3.fill_between([0, 30], [60, 60], y2=[10, 10], color='gray', lw=0)

# order
ax3.zorder = 1 # fills in back
ax1.zorder = 2 # then the line
ax2.zorder = 3 # then the points
ax1.patch.set_visible(False)

plt.show()

这篇关于matplotlib两个Y轴混合Z轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆