如何在pandas图中突出显示区域?

4

我正在比较和绘制两个数组,我想绘制它们,并用某种颜色突出显示数组a小于数组b的区域。这是我正在尝试处理的代码,其中c是数组a小于b的位置:

import pandas
import numpy

numpy.random.seed(10)

df = pandas.DataFrame(numpy.random.randn(10, 2), columns=['a', 'b'])

df['c'] = df['a'] < df['b']

结果生成的数据框如下:

          a         b      c
0  1.331587  0.715279  False
1 -1.545400 -0.008384   True
2  0.621336 -0.720086  False
3  0.265512  0.108549  False
4  0.004291 -0.174600  False
5  0.433026  1.203037   True
6 -0.965066  1.028274   True
7  0.228630  0.445138   True
8 -1.136602  0.135137   True
9  1.484537 -1.079805  False

以下是您需要翻译的内容:

这里有一个我在老实可靠的 MS Paint(已故)制作出来的精美示例,展示了我想要制作的内容:

enter image description here


这并没有展示任何尝试的代码,即使是绘制不带区域的图形。 - Mad Physicist
Pandas使用matplotlib进行绘图,因此我投票将其关闭为重复。 - Mad Physicist
1个回答

9
您可以使用axvspan尝试类似于这样的内容。您可以避免创建专用的c列。
ax = df.plot()

def highlight(indices,ax):
    i=0
    while i<len(indices):
        ax.axvspan(indices[i]-0.5, indices[i]+0.5, facecolor='pink', edgecolor='none', alpha=.2)
        i+=1

highlight(df[df['a'] < df['b']].index, ax)

enter image description here


1
谢谢!对于那些使用datetime指数的人,我做了M15 = dt.timedelta(minutes=15),然后ax.axvspan(indices [i] - M15,indices [i] + M15,...) - Flint O'Brien
1
与其他被标记为重复的帖子不同,这篇文章展示了如何获取多个跨度。 - abhishah901

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接