使用matplotlib将负片条显示为红色,将正片条显示为绿色

2024-09-28 20:59:51 发布

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

我试着改变条形图中条形的颜色,其中负条形应该是红色,正条形应该是绿色。我计算钢筋的值如下:

tickerDf['Momentum'] = tickerDf['Close'].diff(periods=10)

数据帧中的数据,最后一列是Momentum

2020-07-07  180.50  183.95  178.35  183.70  1418976 -4.73
2020-07-08  183.10  184.10  179.35  180.05   757800 7.08
2020-07-09  180.35  185.25  179.90  182.25   739061 -9.13
2020-07-10  181.10  181.70  177.65  177.70   933221 -2.65
2020-07-13  178.15  180.55  176.85  180.35  1088635 6.85

现在我只画了这样的专栏:

ax3.bar(s.index, s['Momentum'])
ax3.axes.yaxis.set_ticklabels([])
ax3.tick_params('x', labelrotation=45)
ax3.set_ylabel('Momentum')

但是我如何绘制负动量值红色和正动量值绿色


Tags: 数据close颜色diff动量条形图set绿色
2条回答

您可以定义颜色数组并传递到bar命令:

colors = ['r' if m > 0 else 'g' for m in df.momentum]
df.plot.bar(y='momentum',color=colors, ax=ax3)

输出:

enter image description here

您可以尝试以下方法:

clrs = ['red' if (x < 0) else 'green' for x in s['Momentum'] ]
ax3.bar(s.index, s['Momentum'], color=clrs)

相关问题 更多 >