【问题标题】:Plotting line with different colors不同颜色的绘图线
【发布时间】:2017-11-24 01:18:01
【问题描述】:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df1 = pd.DataFrame(np.random.randint(0,15,size=(15, 1)))
df2 = pd.DataFrame(np.random.randint(20,35,size=(10, 1)))


frames = [df1, df2]
result = pd.DataFrame(pd.concat(frames))

df3 = result.cumsum()
df3 = df3.reset_index(drop=False)
print(df3)
df3.plot(y=0)
plt.show()

是否可以用两种不同的颜色绘制 df3 线?第一种颜色用于第 0 到 14 行,第二种颜色用于第 15 到 24 行。在某种程度上,我想标记 df1 已结束和 df2 已开始的位置。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    怎么样

    #[...]
    df3 = result.cumsum()
    df3 = df3.reset_index(drop=False)
    plt.plot(df3.mask(df3.apply(lambda x: x.index < 15))[0], color='blue')
    plt.plot(df3.mask(df3.apply(lambda x: x.index > 15))[0], color='green')
    plt.show()
    plt.close()# do not forget this to save you from Runtime Error.
    

    【讨论】:

      【解决方案2】:

      只需用你喜欢的任何颜色绘制你想要的数据框部分,例如df3.iloc[:15,:].plot(color="green").

      import pandas as pd
      import matplotlib.pyplot as plt
      import numpy as np
      
      df1 = pd.DataFrame(np.random.randint(0,15,size=(15, 1)))
      df2 = pd.DataFrame(np.random.randint(20,35,size=(10, 1)))
      
      
      frames = [df1, df2]
      result = pd.DataFrame(pd.concat(frames))
      
      df3 = result.cumsum()
      df3 = df3.reset_index(drop=False)
      print(df3)
      ax = df3.iloc[:15,:].plot(y=0, color="crimson")
      df3.iloc[15:,:].plot(y=0, color="C0", ax=ax)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 2022-11-13
        • 1970-01-01
        • 2011-01-02
        相关资源
        最近更新 更多