Python中的 Matplotlib.axes.Axes.twinx()
Matplotlib是Python中的一个库,它是 NumPy 库的数值数学扩展。 Axes 类包含大部分图形元素:Axis、Tick、Line2D、Text、Polygon 等,并设置坐标系。 Axes 的实例通过回调属性支持回调。
matplotlib.axes.Axes.twinx()函数
matplotlib 库的 axes 模块中的Axes.twinx()函数用于创建共享 xaxis 的双轴。
Syntax: Axes.twinx(self)
Parameters: This method does not accepts any parameters.
Return value: This method is used to returns the following.
- ax_twin : This returns the newly created Axes instance.
下面的示例说明了 matplotlib.axes 中的 matplotlib.axes.Axes.twinx()函数:
示例 1:
# Implementation of matplotlib function
import matplotlib.pyplot as plt
import numpy as np
def GFG1(temp):
return (5. / 9.) * (temp - 32)
def GFG2(ax1):
y1, y2 = ax1.get_ylim()
ax_twin .set_ylim(GFG1(y1), GFG1(y2))
ax_twin .figure.canvas.draw()
fig, ax1 = plt.subplots()
ax_twin = ax1.twinx()
ax1.callbacks.connect("ylim_changed", GFG2)
ax1.plot(np.linspace(-40, 120, 100))
ax1.set_xlim(0, 100)
ax1.set_ylabel('Fahrenheit')
ax_twin .set_ylabel('Celsius')
fig.suptitle('matplotlib.axes.Axes.twinx()\
function Example\n\n', fontweight ="bold")
plt.show()
输出:
示例 2:
# Implementation of matplotlib function
import numpy as np
import matplotlib.pyplot as plt
# Create some mock data
t = np.arange(0.01, 10.0, 0.001)
data1 = np.exp(t)
data2 = np.sin(0.4 * np.pi * t)
fig, ax1 = plt.subplots()
color = 'tab:blue'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color = color)
ax1.plot(t, data1, color = color)
ax1.tick_params(axis ='y', labelcolor = color)
ax2 = ax1.twinx()
color = 'tab:green'
ax2.set_ylabel('sin', color = color)
ax2.plot(t, data2, color = color)
ax2.tick_params(axis ='y', labelcolor = color)
fig.suptitle('matplotlib.axes.Axes.twinx() \
function Example\n\n', fontweight ="bold")
plt.show()
输出: