matplotlib之pyplot模块——添加次坐标轴(第二坐标轴)(twinx())
当前有效matplotlib版本为:3.4.1。次坐标轴次坐标轴也被称为第二坐标轴或副坐标轴,用于在一个图形中显示两个不同坐标尺度的图表。twinx函数twinx函数的功能为创建并返回一个共享x轴的子图。twinx函数的签名为matplotlib.pyplot.twinx(ax=None)。参数ax的值类型为Axes对象,默认值为None即当前子图。twinx函数的功能为创建并返回一个共享x轴的子
·
当前有效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()
更多推荐
已为社区贡献1条内容
所有评论(0)