Pandas Plot One Line Graph With Color Change On Column
My dataframe df = pd.DataFrame({'date': ['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05'], 'b': ['a', 'a', 'b', 'b', 'c'], 'c': [1,2,3,4,5]}) date b
Solution 1:
You basically want to create a new series for each value in column b
. One way to do that is to group on date
and b
and then unstack b
, and the other method is to use pivot
. Then just plot the result.
df.pivot(index='date', columns='b').droplevel(0, axis=1).plot(colors='rbc')
# 'rbc'= ['red', 'blue', 'cyan']
# These colors are based on the column ordering, e.g. 'a', 'b', 'c'.
To be more explicit with the colors:
colors = {
'a': 'red',
'b': 'blue',
'c': 'cyan'
}
(df
.pivot(index='date', columns='b')
.droplevel(0, axis=1)[colors.keys()]
.plot(colors=colors.values())
)
Solution 2:
Let's try:
_, ax = plt.subplots()
df['date'] = pd.to_datetime(df['date'])
colors = {'a':'r', 'b':'b','c':'c'}
for n, g in df.groupby('b'):
g.plot('date','c', marker='o', ax=ax, color=colors[n])
ax.legend()
Output:
Post a Comment for "Pandas Plot One Line Graph With Color Change On Column"