pandas seaborn 或 matplotlib 折线图,线条颜色取决于变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33560789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
seaborn or matplotlib line chart, line color depending on variable
提问by Alexis Eggermont
I have a pandas dataframe with three columns, Date
(timestamp), Color
('red' or 'blue') and Value
(int).
我有一个包含三列Date
(时间戳)、Color
(“红色”或“蓝色”)和Value
(整数)的Pandas数据框。
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 herea 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)
我正在尝试实现这样的目标(只有一行,但有几种颜色)
回答by Anton Protopopov
As I said you could find the answer from the linkI 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
更改颜色时,您需要添加额外的点以使线条连续