简体   繁体   English

如何使用 matplotlib fill_between 作为默认 ylim

[英]How to use matplotlib fill_between for default ylim

Without Fill :无填充:

在此处输入图片说明

With Fill :填充:

在此处输入图片说明

plt.fill_between(n,data)

I want to fill for default y limit.我想填写默认的 y 限制。

Also can I do a gradient fill?我也可以做渐变填充吗?

You can use ax.get_ylim() to get the y limits.您可以使用ax.get_ylim()来获取 y 限制。 ax.fill_between(n, ymin, data) fills the area between the minimum and the curve. ax.fill_between(n, ymin, data)填充最小值和曲线之间的区域。 If you don't supply two y-values for fill_between , 0 is used as default, which in this case is very far away from the actual curve.如果您没有为fill_between提供两个 y 值,则默认使用0 ,在这种情况下,这与实际曲线相距甚远。

The polygon created by fill_between can be extracted and used as a clipping path for a gradient rectangle.可以提取由fill_between创建的多边形并将其用作渐变矩形的剪切路径。

Here is some example code:下面是一些示例代码:

import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
import numpy as np

np.random.seed(123)
n = np.arange(12)
data = np.random.randint(97800, 98400, len(n))
fig, ax = plt.subplots()
ax.plot(n, data, color='dodgerblue')
ymin, ymax = ax.get_ylim()
fill_poly = ax.fill_between(n, ymin, data, color='none')
gradient_rect = ax.imshow(np.arange(256).reshape(-1, 1), extent=[n.min(), n.max(), ymin, ymax],
                      cmap='Blues_r', aspect='auto')
clip_poly = PathPatch(fill_poly.get_paths()[0], transform=ax.transData)
gradient_rect.set_clip_path(clip_poly)
plt.show()

用渐变填充

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM