Matplotlib中fill_between函数在最小和最大边界之间生成一个阴影区域,这对于说明范围很有用。它有一个非常方便的where参数将填充与逻辑范围结合起来,例如,仅填充超过某个阈值的曲线。
在最基本的层面上,fill_between可用于增强图形的视觉外观。让我们比较两个财务数据图,左侧是简单的线图,右侧是实心线。
- 代码解析 (展示Google(GOOG)的每日收盘股价)
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook
首先导入了Matplotlib库(用于绘图)、NumPy库(用于数值操作)、以及Matplotlib的cbook模块(用于获取样本金融数据)。
# 载入一些样本金融数据
r = cbook.get_sample_data('goog.npz')['price_data']
这行代码从Matplotlib的样本数据库中加载了Google(GOOG)的样本金融数据,并将其存储在变量r
中。
# 创建两个共享x和y轴的子图
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)
在这里,创建了一个包含两个子图的图表。ax1
和ax2
分别代表两个子图,它们共享相同的x和y轴(sharex=True
和sharey=True
)。
pricemin = r["close"].min()
计算了从加载的金融数据中获取的最小收盘价,并将其存储在变量pricemin
中。
ax1.plot(r["date"], r["close"], lw=2)
在第一个子图(ax1
)中,绘制了每日收盘价随日期变化的折线图。线条宽度被设置为2(lw=2
)。
ax2.fill_between(r["date"], pricemin, r["close"], alpha=0.7)
在第二个子图(ax2
)中,用颜色填充了最小价格(pricemin
)和收盘价之间的区域。alpha
参数控制填充区域的透明度。
for ax in ax1, ax2:
ax.grid(True)
ax.label_outer()
两个子图都启用了网格线(ax.grid(True)
),并隐藏了外部标签(ax.label_outer()
)。
ax1.set_ylabel('price')
为第一个子图设置了y轴标签为’price’。
fig.suptitle('Google (GOOG) daily closing price')
设置了整个图表的标题。
fig.autofmt_xdate()
自动调整x轴标签的格式,以提高可读性,特别是在处理日期数据时。
- 完整代码
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook
# load up some sample financial data
r = cbook.get_sample_data('goog.npz')['price_data']
# create two subplots with the shared x and y axes
fig, (ax1, ax2) = plt.subplots(2,1, sharex=True, sharey=True)
pricemin = r["close"].min()
ax1.plot(r["date"], r["close"], lw=2)
ax2.fill_between(r["date"], pricemin, r["close"], alpha=0.7)
for ax in ax1, ax2:
ax.grid(True)
ax.label_outer()
ax1.set_ylabel('price')
fig.suptitle('Google (GOOG) daily closing price')
fig.autofmt_xdate()
plt.show()