使用matplotlib的线图/时间序列上的多条线 [英] Multiple lines on line plot/time series with matplotlib
问题描述
我如何在matplotlib或Python上的plot.ly上绘制由分类变量表示的多条迹线?我正在尝试从R复制geom_line(aes(x = Date,y = Value,color = Group)函数.
How do I plot multiple traces represented by a categorical variable on matplotlib or plot.ly on Python? I am trying to replicate the geom_line(aes(x=Date,y=Value,color=Group) function from R.
有没有办法在 Python 上实现这一点,而无需将组放在单独的列中?我是否必须不可避免地重组数据?
Is there a way to achieve this on Python without the need to have the groups in separate columns? Do I have to restructure the data inevitably?
假设我有以下数据:
Date Group Value
1/01/2015 A 50
2/01/2015 A 60
1/01/2015 B 100
2/01/2015 B 120
1/01/2015 C 40
2/01/2015 C 55
1/01/2015 D 36
2/01/2015 D 20
我想在x轴上显示日期,在y轴上显示值,并用不同的彩色线条/迹线表示组类别.
I would like date on the x axis, value on the y axis, and the group categories represented by different coloured lines/traces.
谢谢.
推荐答案
假设您的数据位于pandas数据框 df
中,则在没有分组位于单独列中的情况下很难进行绘制,实际上,很容易一步就完成了这一步,
Assuming your data is in a pandas dataframe df
, it would be hard to plot it without the groups being in separate columns, but that is actually a step very easily done in one line,
df.pivot(index="Date", columns="Group", values="Value").plot()
完整示例:
u = u"""Date Group Value
1/01/2015 A 50
2/01/2015 A 60
1/01/2015 B 100
2/01/2015 B 120
1/01/2015 C 40
2/01/2015 C 55
1/01/2015 D 36
2/01/2015 D 20"""
import io
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(io.StringIO(u), delim_whitespace=True)
df["Date"] = pd.to_datetime(df["Date"])
df.pivot(index="Date", columns="Group", values="Value").plot()
plt.show()
这篇关于使用matplotlib的线图/时间序列上的多条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!