plt.show()参数传递疑问:无显式参数为何能显示图表?
关于matplotlib中plt.show()无参数仍能显示图表的疑问
我在学习Nicolas Vandeput所著《供应链预测数据科学》(Data Science for Supply Chain Forecast)第一章内容时,遇到一个问题:代码里的plt.show()函数没传显式参数却能正常显示图表,但我找不到参数传递的位置。作为Python新手,想知道是不是存在隐式传递参数的方式。
相关代码
主代码
from chap_01_05_moving_average_function import ( moving_average, ) import matplotlib.pyplot as plt d = [28, 19, 18, 13, 19, 16, 19, 18, 13, 16, 16, 11, 18, 15, 13, 15, 13, 11, 13, 10, 12] df = moving_average(d) print(df) df[["Demand", "Forecast"]].plot() df.index.name = "Periods" print("index", df.index.name) df[["Demand", "Forecast"]].plot( figsize=(8, 3), title="Moving average", ylim=(0, 30), style=["-", "--"] ) plt.show()
chap_01_05_moving_average_function.py代码
# page 5 - moving average import numpy as np import pandas as pd def moving_average(d, extra_periods=1, n=3): d = np.array(d) cols = len(d) d = np.append(d, [np.nan] * extra_periods) f = np.full(cols + extra_periods, np.nan) for t in range(n, cols + 1): f[t] = np.mean(d[t - n : t]) f[cols + 1 :] = f[t] df = pd.DataFrame.from_dict({"Demand": d, "Forecast": f, "Error": d - f}) return df # numpy - add arrays ts = np.array([1, 2, 3, 4, 5, 6]) ts2 = np.array([10, 20, 30, 40, 50, 60]) print(ts + ts2) # numpy - list alist = [1, 2, 3] alistmean = np.mean(alist) print(alistmean) # slicing alist = ["cat", "dog", "mouse"] print(alist[1]) anarray = np.array([1, 2, 3]) print(anarray[0]) # slicing - start:end alist = ["cat", "dog", "mouse"] print(alist[1:]) anarray = np.array([1, 2, 3]) print(anarray[:1]) # slicing - negative alist = ["cat", "dog", "mouse"] print(alist[-1]) print(alist[:-1])
解答
plt.show()本身就不需要强制传递参数,它的工作逻辑是读取matplotlib维护的当前绘图上下文状态来显示图表,这就是你疑惑的"隐式传递"本质:
- 当你调用
df[["Demand", "Forecast"]].plot()时,pandas的plot方法会自动调用matplotlib的API创建图表元素,并将这些元素关联到matplotlib默认的画布(Figure)和坐标轴(Axes)对象上。matplotlib会自动跟踪当前所有已创建的Figure实例。 - 调用
plt.show()时,如果没有传入具体的Figure对象,它会自动查找当前上下文里所有已创建的图表并显示出来。
如果需要显式指定要显示的图表,可以先保存plot的返回值(坐标轴对象),再传入对应的Figure:
ax = df[["Demand", "Forecast"]].plot(figsize=(8, 3), title="Moving average", ylim=(0, 30), style=["-", "--"]) plt.show(ax.figure) # 显式传入目标画布对象
日常使用中,隐式调用已经足够满足需求,因为matplotlib会自动管理你创建的所有图表。
内容的提问来源于stack exchange,提问作者Abdulsalam Almahdi
相关产品推荐
相关产品推荐

