seaborn or matplotlib line chart, line color depending on variable

情到浓时终转凉″ 提交于 2019-12-12 02:47:25

问题


I have a pandas dataframe with three columns, Date(timestamp), Color('red' or 'blue') and Value(int).

I am currently getting a line chart from it with the following code:

import matplotlib.pyplot as plt
import pandas as pd
Dates=['01/01/2014','02/01/2014','03/01/2014','04/01/2014','05/01/2014','06/01/2014','07/01/2014']
Values=[3,4,6,5,4,5,4]
Colors=['red','red','blue','blue','blue','red','red']
df=pd.DataFrame({'Dates':Dates,'Values':Values,'Colors':Colors})
df['Dates']=pd.to_datetime(df['Dates'],dayfirst=True)

grouped = df.groupby('Colors')
fig, ax = plt.subplots()

for key, group in grouped:
   group.plot(ax=ax, x="Dates", y="Values", label=key, color=key)

plt.show()

I'd like the line color to depend on the 'color' columns. How can I achieve that?

I have seen here a similar question for scatterplots, but it doesn't seem I can apply the same solution to a time series line chart.

My output is currently this:

I am trying to achieve something like this (one line only, but several colors)


回答1:


As I said you could find the answer from the link I attached in the comment:

import matplotlib.pyplot as plt
import pandas as pd
Dates=['01/01/2014','02/01/2014','03/01/2014','03/01/2014','04/01/2014','05/01/2014']
Values=[3,4,6, 6,5,4]
Colors=['red','red', 'red', 'blue','blue','blue']
df=pd.DataFrame({'Dates':Dates,'Values':Values,'Colors':Colors})
df['Dates']=pd.to_datetime(df['Dates'],dayfirst=True)

grouped = df.groupby('Colors')
fig, ax = plt.subplots(1)

for key, group in grouped:
   group.plot(ax=ax, x="Dates", y="Values", label=key, color=key)

When color changing you need to add extra point to make line continuous



来源:https://stackoverflow.com/questions/33560789/seaborn-or-matplotlib-line-chart-line-color-depending-on-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!