【问题标题】:Filling specified regions in a matplotlib plot在 matplotlib 图中填充指定区域
【发布时间】:2019-02-27 15:35:21
【问题描述】:

我正在用 matplotlib 创建一个基本的线图。 x 轴代表百分位数。 y 轴以秒为单位表示时间。我想对代表每个百分位数的图表区域进行着色(例如,0.25 及以下、>0.25 和

这是我当前的代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rc
from matplotlib import mlab
import matplotlib.ticker as mtick
import seaborn as sns

testx = np.array([0.0, 0.05, 0.25, 0.5, 0.9])
testy = np.array([0,5,14.75,40,96.1,120])

plt.plot(testx, testy)
plt.fill_between(testx, testy, where=(testx <= 0.25))
plt.fill_between(testx, testy, where=(testx > 0.25) & (testx <= 0.5))

这将返回以下图:

可以看出,它正确地对 testx 小于或等于 0.25 的第一个 fill_between 进行了着色。但之后它不会遮蔽任何东西。

预期的输出是为多个范围多次再现阴影。

非常感谢任何帮助!

【问题讨论】:

  • 当您第二次调用fill_between 时,请尝试将您的情况用另一对括号括起来。即...where=((testx &gt; 0.25) &amp; (testx &lt;= 0.5)))
  • 谢谢,FChm。不幸的是,这并没有导致正确的填充。
  • 哦,这是因为您没有足够的数据点......即,testx = np.array([0.0, 0.05, 0.25, 0.5, 0.9]) 您的 fill_between 条件只有一个值,即 True(其中 test_x=0.5)。再次尝试沿 x 进行更密集的采样。 (即test_x = np.linspace(0,1,100),您的代码将正常工作。
  • 这行得通!谢谢!但我不知道如何将您的评论作为答案。
  • 你去吧,我把它转换成答案了。

标签: python matplotlib plot


【解决方案1】:

这是因为您没有足够的数据点。

即,

testx = np.array([0.0, 0.05, 0.25, 0.5, 0.9])

这意味着你的条件:

where = ((testx > 0.25) & (testx <= 0.5))

只有一个值等于True (where = [False False False True False]) 和fill_between 之间没有填充位置。

您可以通过以下方式解决此问题:

a) 使用更密集的“x”采样(即 test_x = np.linspace(0,1,100)

b) 更改条件以包含 x 等于 0.25 的值:

where = ((testx >= 0.25) & (testx <= 0.5))

【讨论】:

  • 干杯!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
  • 2016-07-15
  • 2021-01-03
相关资源
最近更新 更多