I am trying to plot a line that should be colored in a way that represents the trend of the graph. For example, if it is increasing it should be green, while if it is decreasing it should be red.
I can represent this trend plotting dots simply using a shifted dataframe:
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']])
I know that matplotlib does not allow using different colors in the same line plot, but is there any workaround to this without making it utterly complicated?
I have thought about plotting two different dataframes using the Increase mask but the problem is that the line would be plotted continuedly, so all dots would be connected, while I would need it to be split into different pieces made up of segments.