我将尝试绘制一条线,它的颜色应该以表示图表趋势的方式进行着色。例如,如果增加应该是绿色,而如果减少则应该是红色。
我可以使用移动后的数据框来简单地表示这种趋势绘制点图形:
我可以使用移动后的数据框来简单地表示这种趋势绘制点图形:
dates = ['2018-01-{}'.format(d) for d in range(1, 32)]
vals = [1, 2, 3, 4, 6, 9, 12, 11, 10, 8, 4, 10, 15, 17, 17, 18, 18, 17, 16, 19, 22, 23, 23, 25, 28, 33, 30, 25, 24,
20, 18]
df = pd.DataFrame(data=vals, columns=['Value'])
df.set_index(pd.to_datetime(dates), inplace=True)
df_shifted = df.shift()
df_shifted.iloc[0] = df_shifted.iloc[1]
mask_inc = df >= df_shifted
df['Increase'] = mask_inc['Value']
fig, ax = plt.subplots()
ax.plot(df['Value'], color='#ededed')
color = {True: 'green', False: 'red'}
for index, row in df.iterrows():
ax.plot(index, row['Value'], 'o', color=color[row['Increase']])
我知道在matplotlib中无法在同一条线图中使用不同的颜色,但有没有什么解决方法可以使它不那么复杂?
我考虑过使用增量掩码绘制两个不同的数据框,但问题是该线将被连续绘制,因此所有点都将连接在一起,而我需要将其分成由线段组成的不同部分。