从堆叠数据帧填充

2024-06-07 21:15:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

symbol       DAL        MS       QQQ       SPY      TLT  XLE
symbol                                                      
DAL          NaN       NaN       NaN       NaN      NaN  NaN
MS      0.560979       NaN       NaN       NaN      NaN  NaN
QQQ     0.621045  0.789771       NaN       NaN      NaN  NaN
SPY    -0.576444 -0.843485 -0.953304       NaN      NaN  NaN
TLT     0.186840  0.421957  0.333320 -0.347808      NaN  NaN
XLE     0.115093  0.578970  0.559711 -0.701126  0.38047  NaN

然后对数据帧进行堆叠和排序,并将结果绘制为条形图,如下所示:

^{pr2}$

enter image description here

我现在要做的是(没有成功)不是把它画成条形图,而是通过填充零下和零上的区域来绘制它。我的猜测是我应该在类似于以下示例之间使用填充符:link

ax.fill_between(dfstacked.index, 0, dfstacked.values, where = dfstacked.values > 0, interpolate=True)
ax.fill_between(dfstacked.index, dfstacked.values, 0, where = dfstacked.values < 0, interpolate=True)

我得到错误:TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''


Tags: the数据绘制nanaxsymbolmsdal
3条回答

您可以使用widthedgecolor参数来获得看起来不像直方图的内容。在

x=[1,2,3,4,5,6]
y=[-3,-1,5,3,4,2]

plt.bar(x,y,color='b',width=1,edgecolor="none")

enter image description here

你的语法有点不对劲。在您的例子中,fill_between需要X值,然后是要填充的Y值,然后是Y值。在

下面是一个小例子:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

s = pd.Series([-4,-3,-2,-1,0,1,2,3,4,5,6,7,8])
x = np.arange(len(s))
plt.fill_between(x,0,s)

area under curve

然后您可以使用您的indexset_xticklabels。在

您尝试^{}

dfstacked = dfstacked.reset_index(drop=True)
print dfstacked
0    -0.953304
1    -0.843485
2    -0.701126
3    -0.576444
4    -0.347808
5     0.115093
6     0.186840
7     0.333320
8     0.380470
9     0.421957
10    0.559711
11    0.560979
12    0.578970
13    0.621045
14    0.789771
dtype: float64

然后从multiindex设置axis x

^{pr2}$

graph01

相关问题 更多 >

    热门问题