我有以下数据框:
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
然后我对数据帧进行堆叠和排序,并将结果绘制为条形图,如下所示:
dfstacked = corr_df.stack().order()
dfstacked.plot(kind='bar')
symbol symbol
SPY QQQ -0.953304
MS -0.843485
XLE SPY -0.701126
SPY DAL -0.576444
TLT SPY -0.347808
XLE DAL 0.115093
TLT DAL 0.186840
QQQ 0.333320
XLE TLT 0.380470
TLT MS 0.421957
XLE QQQ 0.559711
MS DAL 0.560979
XLE MS 0.578970
QQQ DAL 0.621045
MS 0.789771
我现在想做的(没有成功)不是将其绘制为条形图,而是通过填充零以下和以上的区域来绘制它。我的猜测是我应该使用类似于以下示例的 fill_between: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' 不支持输入类型,并且根据转换规则 ''safe'' 无法将输入安全地强制转换为任何受支持的类型
最佳答案
你试试reset_index
:
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
:
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
dfstacked = corr_df.stack().order()
ticklabels = dfstacked.index.tolist()
dfstacked = dfstacked.reset_index(drop=True)
print dfstacked
ax = dfstacked.plot()
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)
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.xticks(rotation=90)
plt.show()
关于python - 来自堆叠数据帧的 fill_between,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35173310/