matplotlib.pyplot.twinx()函数 - 用于创建和返回共享x轴的第二个轴

matplotlib.pyplot.twinx()函数

Matplotlib是Python中的一个库,它是NumPy库的数值-数学扩展。Pyplot是一个基于状态的Matplotlib模块接口,该模块提供了一个类似matlab的接口。

示例代码

# sample code
import matplotlib.pyplot as plt 
    
plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) 
plt.show() 

输出:

matplotlib.pyplot.twinx()函数

matplotlib.pyplot.twinx()函数

matplotlib库的pyplot模块中的twinx()函数用于创建和返回共享x轴的第二个轴。

语法:

matplotlib.pyplot.twinx(ax=None)

参数:此方法不接受任何参数。

返回:返回与x轴共享的第二个轴

下面的例子演示了matplotlib.pyplot.twinx()函数在matplotlib.pyplot中的作用:

示例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(0, 120, 100))
ax1.set_xlim(30, 100)
   
ax1.set_ylabel('Fahrenheit')
ax_twin .set_ylabel('Celsius')
   
fig.suptitle('matplotlib.pyplot.twinx() function \
Example\n\n', fontweight ="bold")
plt.show()

输出:

matplotlib.pyplot.twinx()函数

示例2

# Implementation of matplotlib function
import numpy as np
import matplotlib.pyplot as plt
   
# Create some mock data
t = np.arange(0.01, 20.0, 0.001)
data1 = np.exp(t)
data2 = np.sin(0.3 * 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.pyplot.twinx() function \
Example\n\n', fontweight ="bold")
plt.show()

输出:

matplotlib.pyplot.twinx()函数

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程