当前有效matplotlib版本为:3.4.1

次坐标轴

次坐标轴也被称为第二坐标轴或副坐标轴,用于在一个图形中显示两个不同坐标尺度的图表。

twinx函数

twinx函数的功能为创建并返回一个共享x轴的子图。

twinx函数的签名为matplotlib.pyplot.twinx(ax=None)。参数ax的值类型为Axes对象,默认值为None即当前子图。

twinx函数的功能为创建并返回一个共享x轴的子图。新子图将会与ax重叠,新创建的子图的x轴将会隐藏,y轴将会位于子图的右侧。

twinx函数的返回值为 Axes对象,即新创建的子图。

twinx函数相关源码

matplotlib.pyplot.twinx()

def twinx(ax=None):
    if ax is None:
        ax = gca()
    ax1 = ax.twinx()
    return ax1

matplotlib.Axes.twinx()

def twinx(self):
    ax2 = self._make_twin_axes(sharex=self)
    ax2.yaxis.tick_right()
    ax2.yaxis.set_label_position('right')
    ax2.yaxis.set_offset_position('right')
    ax2.set_autoscalex_on(self.get_autoscalex_on())
    self.yaxis.tick_left()
    ax2.xaxis.set_visible(False)
    ax2.patch.set_visible(False)
    return ax2

matplotlib.Axes._make_twin_axes()

def _make_twin_axes(self, *args, **kwargs):
    """Make a twinx axes of self. This is used for twinx and twiny."""
    # Typically, SubplotBase._make_twin_axes is called instead of this.
    if 'sharex' in kwargs and 'sharey' in kwargs:
        raise ValueError("Twinned Axes may share only one axis")
    ax2 = self.figure.add_axes(
        self.get_position(True), *args, **kwargs,
        axes_locator=_TransformedBoundsLocator(
            [0, 0, 1, 1], self.transAxes))
    self.set_adjustable('datalim')
    ax2.set_adjustable('datalim')
    self._twinned_axes.join(self, ax2)
    return ax2

案例

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt

# 构造数据
t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)
# 第一个子图
ax1 = plt.gca()
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color='r')
ax1.plot(t, data1, color='r')
ax1.tick_params(axis='y', labelcolor='r')
# 创建与ax1共享x轴的第二个子图
ax2 = ax1.twinx() 
ax2.set_ylabel('sin', color='b') 
ax2.plot(t, data2, color='b')
ax2.tick_params(axis='y', labelcolor='b')

plt.tight_layout()
plt.show()
Logo

鸿蒙生态一站式服务平台。

更多推荐