Python中Matplotlib使用fill_between函数在最小和最大边界之间生成一个阴影区域 以google每日收盘估价历史数据为例

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)

在这里,创建了一个包含两个子图的图表。ax1ax2分别代表两个子图,它们共享相同的x和y轴(sharex=Truesharey=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()
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pandas120

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值