如何在 Matplotlib 中的子圖之間共享次要 Y 軸?
要在 matplotlib 中的子圖之間共享次要 Y 軸,我們可以採取以下步驟:
建立用於資料點的**x**。
向當前圖形新增一個子圖,**nrows=2**,**ncols=1**,位於**索引=1 (ax0)**
使用 twinx() 方法,建立一個具有共享 X 軸但獨立 Y 軸的軸副本 (ax1)。
向當前圖形新增一個子圖,**nrows=2**,**ncols=1**,位於**索引=2 (ax2)**
使用 twinx() 方法,建立一個具有共享 X 軸但獨立 Y 軸的軸副本 (ax3)。
使用**get_shared_y_axes()**方法,返回對 Y 軸共享軸**Grouper**物件的引用。
建立具有不同顏色、x 和 y 資料點的曲線**c1**、**c2**、**c3** 和**c4**。
要將圖例框移動到圖形的左上方,請使用帶**bbox_to_anchor**的**legend**方法。
要顯示圖形,請使用**show()**方法。
示例
import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-2, 2, 10) ax0 = plt.subplot(211) ax1 = ax0.twinx() # Create a twin of Axes with a shared x-axis but independent y-axis. ax2 = plt.subplot(212) ax3 = ax2.twinx() # Create a twin of Axes with a shared x-axis but independent y-axis. ax1.get_shared_y_axes().join(ax1, ax3) c1, = ax0.plot(x, np.sin(x), c='red') c2, = ax1.plot(x, np.cos(x), c='blue') c3, = ax2.plot(x, np.tan(x), c='green') c4, = ax3.plot(x, np.exp(x), c='yellow') plt.legend([c1, c2, c3, c4], ["y=sin(x)", "y=cos(x)", "y=tan(x)", "y=exp(x)"], loc = "upper left", bbox_to_anchor=(.070, 2.25)) plt.show()
輸出
廣告