【问题标题】:Show negativ bars as red and positive as green with matplotlib使用 matplotlib 将负条显示为红色,将正条显示为绿色
【发布时间】:2020-11-02 22:04:53
【问题描述】:

我尝试更改条形图中的条形颜色,其中负数条应为红色,正数条应为绿色。我计算条形的值如下:

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

dataframe中的数据,最后一列是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')

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

【问题讨论】:

标签: python python-3.x pandas matplotlib


【解决方案1】:

你可以试试这样的:

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

【讨论】:

    【解决方案2】:

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

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

    输出:

    【讨论】:

      猜你喜欢
      • 2019-10-31
      • 1970-01-01
      • 2011-11-26
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-03
      • 2014-05-14
      相关资源
      最近更新 更多