我想绘制一个条形图,其中每个条形的颜色取决于该值是大于还是小于先前的值。我可以通过列表理解来做到这一点吗?我的猜测是它看起来像这样:
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)
输出:
关于python - 我可以绘制条形图,其中每个条形的颜色取决于该值是大于还是小于先前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238712/