seaborn 或 matplotlib 折线图,线条颜色取决于变量 [英] seaborn or matplotlib line chart, line color depending on variable
问题描述
我有一个熊猫数据框,其中有三列,分别是 Date
(时间戳), Color
(红色"或蓝色")和 Value
(int).
我目前正在使用以下代码从中获取折线图:
将matplotlib.pyplot导入为plt将熊猫作为pd导入日期=['01/01/2014'、'02/01/2014'、'03/01/2014'、'04/01/2014'、'05/01/2014'、'06/01/2014',"2014年7月1日"]值= [3,4,6,5,4,5,4]颜色=['红色','红色','蓝色','蓝色','蓝色','红色','红色']df=pd.DataFrame({'Dates':Dates,'Values':Values,'Colors':Colors})df ['Dates'] = pd.to_datetime(df ['Dates'],dayfirst = True)分组= df.groupby('颜色')无花果,ax = plt.subplots()对于关键,分组分组:group.plot(ax=ax, x="Dates", y="Values", label=key, color=key)plt.show()
我希望线条颜色取决于颜色"列.我该如何实现?
我在
我正在尝试实现这样的功能(仅一行,但有几种颜色)
正如我所说,您可以从link 我附在评论中:
将matplotlib.pyplot导入为plt将熊猫作为pd导入日期 = ['01/01/2014'、'02/01/2014'、'03/01/2014'、'03/01/2014'、'04/01/2014','05/01/2014']值 = [3, 4, 6, 6, 5, 4]颜色= [红色",红色",红色",蓝色",蓝色",蓝色"]df = pd.DataFrame({'Dates':Dates,'Values':Values,'Colors':Colors})df ['Dates'] = pd.to_datetime(df ['Dates'],dayfirst = True)分组= df.groupby('颜色')无花果,ax = plt.subplots(1)对于关键,分组分组:group.plot(ax = ax,x =日期",y =值",label =键,color =键)
当颜色改变时,你需要添加额外的点以使线条连续
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)
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
这篇关于seaborn 或 matplotlib 折线图,线条颜色取决于变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!