14.面向对象API绘图
14.1.图中图 (A Plot inside of Another Plot)
14.2.设定绘图范围 (Setting the Plot Range)
14.3.对数尺度(Logarithmic Scale)
14.面向对象API绘图
Matplotlib绘图库的操作是通过API实现的,一种操作方法是类似MATLAB的函数接口的API;另一种操作方法是面向对象的API。这两种API可以并行使用,不过函数接口的API的易用性明显好于面向对象的API。
就像Python本身一样,Matplotlib是以面向对象的方式编程和设计的。当使用多个图形时,或者当一个图形由多个子图组成时,使用图形对象方法的优点就会显现出来。
在下面的示例中,我们以面向对象的方式创建一个绘图。首先创建一个新的figure实例。将其引用存储在一个Figure类实例,即变量figure实例。将其引用存储在一个Figure类实例,即变量fig中。然后,我们fig中使用add_axes方法创建一个新的轴的实例。
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
X = np.arange(0,10)
Y = np.random.randint(1, 20, size=10)
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
axes = fig.add_axes([left, bottom, width, height])
axes.plot(X, Y, 'b')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')
plt.show()
在不使用figure实例的情况下,代码如下所示:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
X = np.arange(0,10)
Y = np.random.randint(1, 20, size=10)
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
axes = fig.add_axes([left, bottom, width, height])
axes.plot(X, Y, 'b')
axes.set_xlabel('xxxxxxxxxxxxx')
axes.set_ylabel('yyyyyyyyyyyyy')
axes.set_title('title biaoti')
plt.show()
14.1.图中图 (A Plot inside of Another Plot)
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
X = [1, 2, 3, 4, 5, 6, 7]
Y = [1, 3, 4, 2, 5, 8, 6]
axes1 = fig.add_axes([0.1, 0.1, 0.9, 0.9]) # main axes
# add_axes 参数rect The dimensions [left, bottom, width, height] of the new axes.
# All quantities are in fractions of figure width and height.
axes2 = fig.add_axes([0.2, 0.6, 0.4, 0.3]) # inside axes
# main figure
axes1.plot(X, Y, 'r')
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('title')
# insert
axes2.plot(Y, X, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('title inside')
plt.show()
14.2.设定绘图范围 (Setting the Plot Range)
配置轴的范围可以通过在轴对象中使用set_ylim和set_xlim方法来完成。 使用axis(‘tight’),可以自动创建"tightly fitted" 的轴范围:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(10, 4))
x = np.arange(0, 5, 0.25)
axes[0].plot(x, x**2, x, x**3)
axes[0].set_title("default axes ranges")
axes[1].plot(x, x**2, x, x**3)
axes[1].axis('tight')
axes[1].set_title("tight axes")
axes[2].plot(x, x**2, x, x**3)
axes[2].set_ylim([0, 60])
axes[2].set_xlim([2, 5])
axes[2].set_title("custom axes range")
plt.show()
14.3.对数尺度(Logarithmic Scale)
可以为一个或两个轴设置对数尺度。使用接受一个参数(值为log)的set_xscale和set_yscale方法分别设置每个轴的scale:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
x = np.arange(0, 5, 0.25)
ax.plot(x, x ** 2, x, x ** 3)
ax.set_yscale("log")
plt.show()