Liz*_*iza 5 python matplotlib pandas
我正在处理以下数据框(仅用于说明,实际df非常大):
   seq          x1         y1
0  2           0.7725      0.2105
1  2           0.8098      0.3456
2  2           0.7457      0.5436
3  2           0.4168      0.7610
4  2           0.3181      0.8790
5  3           0.2092      0.5498
6  3           0.0591      0.6357
7  5           0.9937      0.5364
8  5           0.3756      0.7635
9  5           0.1661      0.8364
尝试为上述坐标绘制多个折线图(x为"x1对y为"y1").
具有相同"seq"的行是一条路径,并且必须被绘制为一条单独的线,就像对应于seq = 2的所有x,y坐标属于一条线,依此类推.
我能够绘制它们,但是在单独的图形上,我想要在同一图表上的所有行,使用子图,但不能正确.
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib notebook
df.groupby("seq").plot(kind = "line", x = "x1", y = "y1")
这将创建100个图形(等于唯一seq的数量).建议我获取同一图表上所有行的方法.
**更新*
为解决上述问题,我实现了以下代码:
     fig, ax = plt.subplots(figsize=(12,8))
     df.groupby('seq').plot(kind='line', x = "x1", y = "y1", ax = ax)
     plt.title("abc")
     plt.show()
现在,我想要一种方法来绘制具有特定颜色的线条.我是集群1中seq = 2和5的聚类路径; 和另一个集群中seq = 3的路径.
因此,群集1下面有两行,我想要红色,而群集2下面有一行,可以是绿色.
我该怎么办呢?
考虑数据框 df
df = pd.DataFrame(dict(
        ProjID=np.repeat(range(10), 10),
        Xcoord=np.random.rand(100),
        Ycoord=np.random.rand(100),
    ))
然后我们像这样创造抽象艺术
df.set_index('Xcoord').groupby('ProjID').Ycoord.plot()
如本例所示,您需要在绘图之前初始化轴
import pandas as pd
import matplotlib.pylab as plt
import numpy as np
# random df
df = pd.DataFrame(np.random.randint(0,10,size=(25, 3)), columns=['ProjID','Xcoord','Ycoord'])
# plot groupby results on the same canvas 
fig, ax = plt.subplots(figsize=(8,6))
df.groupby('ProjID').plot(kind='line', x = "Xcoord", y = "Ycoord", ax=ax)
plt.show()
其他方式:
for k,g in df.groupby('ProjID'):
  plt.plot(g['Xcoord'],g['Ycoord'])
plt.show()