1
在pyplot中,可以使用zorder
選項或更改plot()
命令的順序來更改不同圖形的順序。但是,通過ax2 = twinx()
添加替代軸時,新軸將始終覆蓋舊軸(如documentation中所述)。PyPlot將替代y軸移動到背景
是否可以改變軸的順序以將替代(孿生)y軸移動到背景?
在下面的例子中,我想顯示在直方圖上的頂部的藍色線:
import numpy as np
import matplotlib.pyplot as plt
import random
# Data
x = np.arange(-3.0, 3.01, 0.1)
y = np.power(x,2)
y2 = 1/np.sqrt(2*np.pi) * np.exp(-y/2)
data = [random.gauss(0.0, 1.0) for i in range(1000)]
# Plot figure
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax2.hist(data, bins=40, normed=True, color='g',zorder=0)
ax2.plot(x, y2, color='r', linewidth=2, zorder=2)
ax1.plot(x, y, color='b', linewidth=2, zorder=5)
ax1.set_ylabel("Parabola")
ax2.set_ylabel("Normal distribution")
ax1.yaxis.label.set_color('b')
ax2.yaxis.label.set_color('r')
plt.show()
編輯:由於某些原因,我無法上傳由該代碼生成的圖像。我會稍後再試。
我想按照這個指導http://matplotlib.1069221.n5.nabble.com/Control-twinx-series-zorder-ax2-series-behind-ax1-series-or-place-ax2- on-left-ax1-on-right-td12994.html並使用'ax1.set_zorder(ax2.get_zorder()+ 1)' – daryl
有關如何在不同軸上繪製不同藝術家的問題,請參見[這個quesiton](https://stackoverflow.com/questions/48619933/interchanging-the-zorders-on-individual-artists-from-two-axes) – ImportanceOfBeingErnest