且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

matplotlib两个Y轴混合Z轴

更新时间:2023-11-09 21:53:46

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

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