python - 我可以绘制条形图,其中每个条形的颜色取决于该值是大于还是小于先前的值

标签 python pandas matplotlib

我想绘制一个条形图,其中每个条形的颜色取决于该值是大于还是小于先前的值。我可以通过列表理解来做到这一点吗?我的猜测是它看起来像这样:

import pandas as pd
import matplotlib.pyplot as plt

DateRange = pd.date_range('1/31/2019', '6/30/2019', freq='M')
df = pd.DataFrame({'Values':[1,3,2,4,3,5]}, index=DateRange)

clrs = ['green' if row > row.shift(1) else 'red' for row in df['Values']]
plt.bar(df.index, df['Values'], width=5, color=clrs)

最佳答案

是的,您只需要传递正确的颜色:

DateRange = pd.date_range('1/31/2019', '6/30/2019', freq='M')
df = pd.DataFrame({'Values':[1,3,2,4,3,5]}, index=DateRange)

# notice the difference with your code
clrs = np.where(df['Values'].diff().gt(0), 'g', 'r')

plt.bar(df.index, df['Values'], width=5, color=clrs)

输出:

enter image description here

关于python - 我可以绘制条形图,其中每个条形的颜色取决于该值是大于还是小于先前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238712/

相关文章:

python - 如何删除该类中某个类的实例?

python - iloc 和 loc 有何不同?

python-2.7 - 如何在 python pandas 中处理这种复杂的逻辑?

pandas - 具有两个 Y 轴和公共(public) X 轴的 Matplotlib 条形图

python - 如何向下移动颜色条标签?

python - networkx draw_networkx_edges capstyle

python - 三角函数寻找景观能见度

python - 发送 DKIM 签名的电子邮件 - Python

python - python中的ANOVA使用带有statsmodels或scipy的pandas数据框?

python - 分组后计算数据框中某些值的数量