Pandas面积图插值/阶梯样式

6

有没有办法在pandas区域图中禁用插值? 我想要一个“阶梯式”区域图。 例如,在正常的线性图中可以指定:

import pandas as pd
df = pd.DataFrame({'x':range(10)})
df.plot(drawstyle = 'steps') # this works
#df.plot(kind = 'area', drawstyle = 'steps') # this does not work

我正在使用 Python 2.7 和 Pandas 0.14.1。非常感谢您的帮助。

嘿,我解决了我最初建议的变通方法。我认为你不会得到任何更好的内置功能。 - cphlewis
3个回答

5

最近,.fill_between() 的一个更新已经随着 matplotlib 版本 1.5.0 发布,它允许填充两个阶梯函数之间的区域。这甚至适用于 Pandas 时间序列。

由于存在参数 step='pre',因此可以像这样使用:

# For error bands around a series df
ax.fill_between(df.index, df - offset, df + offset, step='pre', **kwargs)

# For filling the whole area below a function
ax.fill_between(df.index, df, 0, step='pre', **kwargs)

我认为有意义的其他关键字参数例如alpha=0.3lw=0


2
据我所知,df.plot(drawstyle="steps")甚至不会存储计算的步进顶点;
out = df.plot(kind = 'line', drawstyle = 'steps') # stepped, not filled
stepline = out.get_lines()[0]
print(stepline.get_data())

(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])),因此我认为你需要自己编写代码。这意味着在点列表中的每个 (x[i],y[i]) 后面直接插入 (x[i+1],y[i])
df = pd.DataFrame({'x':range(10)})
x = df.x.values
xx = np.array([x,x])
xx.flatten('F')
doubled = xx.flatten('F') # NOTE! if x, y weren't the same, need a yy
plt.fill_between(doubled[:-1], doubled[1:], label='area')
ax = plt.gca()
df.plot(drawstyle = 'steps', color='red', ax=ax) 

enter image description here


我不知道Pandas是否可以绘制它,但是matplotlib可以使用Pandas时间序列数据框来完成。有新的问题吗? - cphlewis

1

使用面积图不可能实现您想要的效果,但您可以使用堆叠条形图来达到目的。

import pandas as pd
df = pd.DataFrame({'x':range(10)})
df.plot(kind="bar",stacked=True,width = 1)

enter image description here


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