代码之家  ›  专栏  ›  技术社区  ›  00__00__00

多次呼叫pd后颜色一致。数据帧。绘图()

  •  1
  • 00__00__00  · 技术社区  · 8 年前

    我有一个数据框 v 里面有一些数字数据。

    v=pd.DataFrame(data=np.random.rand(300,3))
    

    我想在同一个 matplotlib 图:

    • 散点图
    • 相同点的移动平均值

    我使用 pd.DataFrame.plot()

    plt.figure()
    v.plot(style='o',legend=False,ax=plt.gca(),alpha=0.2,ls='')
    v.rolling(7).mean().plot(legend=False,ax=plt.gca())
    

    这很好用。

    但是,使用第一个绘图绘制的点将根据其行号进行着色。第二个图中的线条也是如此。

    我希望这两种颜色在两个plot命令之间保持一致,因此 通过移动平均获得的线具有与散射中相同的颜色。怎么才能做到呢?

    下面是我运行代码得到的结果。 显然,我不知道红线是对应于绿橙色还是蓝色点。。。

    enter image description here

    1 回复  |  直到 8 年前
        1
  •  2
  •   Vivek Kalyanarangan    8 年前

    原件

    我相信你需要-

    %matplotlib inline # only for jupyter notebooks
    import pandas as pd
    from matplotlib import pyplot as plt
    import numpy as np
    
    colors = {0: 'red', 1:'green', 2:'blue'}
    v=pd.DataFrame(data=np.random.rand(300,3))
    plt.figure()
    v.plot(marker='o',legend=False,ax=plt.gca(),ls='', alpha=0.2, color=colors.values())
    v.rolling(7).mean().plot(legend=False,ax=plt.gca(), color=colors.values())
    

    更新

    随你的便-

    选项1(无额外费用 cm 依赖关系)

    colors_rand = np.random.rand(len(v.columns),3)
    v.plot(marker='o',legend=False,ax=plt.gca(),ls='', alpha=0.5, color=colors_rand )
        v.rolling(7).mean().plot(legend=False,ax=plt.gca(), color=colors_rand )
    

    选项2(根据OP的建议)

    v.plot(marker='o',legend=False,ax=plt.gca(),ls='', alpha=0.5, colors=cm.rainbow(np.linspace(0,1,v.shape[1]) ))
    v.rolling(7).mean().plot(legend=False,ax=plt.gca(), colors=cm.rainbow(np.linspace(0,1,v.shape[1]) ))