【问题标题】:Changing the order of pandas/matplotlib line plotting without changing data order在不更改数据顺序的情况下更改 pandas/matplotlib 线图的顺序
【发布时间】:2021-02-15 09:40:48
【问题描述】:

举个例子:

df = pd.DataFrame(np.random.randint(1,10, size=(8,3)), columns=list('XYZ'))
df.plot(linewidth=10)

绘制顺序将最后一列放在最上面:

我怎样才能使它保持数据和图例的顺序,但改变行为,使其在 Z 上的 Y 上绘制 X?

(我知道我可以更改数据列的顺序并编辑图例的顺序,但我希望有一种更简单的方法,让数据保持原样)

更新:使用的最终解决方案:

(感谢 r-beginners)我使用 get_lines 来修改每个绘图的 z 顺序

df = pd.DataFrame(np.random.randint(1,10, size=(8,3)), columns=list('XYZ'))
fig = plt.figure()
ax = fig.add_subplot(111)
df.plot(ax=ax, linewidth=10)
lines = ax.get_lines()
for i, line in enumerate(lines, -len(lines)):
    line.set_zorder(abs(i))
fig

在笔记本中产生:

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    获取默认 zorder 并按所需顺序对其进行排序。

    
    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    np.random.seed(2021)
    
    df = pd.DataFrame(np.random.randint(1,10, size=(8,3)), columns=list('XYZ'))
    ax = df.plot(linewidth=10)
    l = ax.get_children()
    print(l)
    l[0].set_zorder(3)
    l[1].set_zorder(1)
    l[2].set_zorder(2)
    
    

    定义前

    定义zorder后

    【讨论】:

      【解决方案2】:

      我只是把这个答案放在这里,因为它是解决问题的方法,但可能不是你要找的。​​p>

      import matplotlib.pyplot as plt
      import pandas as pd
      import numpy as np
      
      # generate data
      df = pd.DataFrame(np.random.randint(1,10, size=(8,3)), columns=list('XYZ'))
      
      # read columns in reverse order and plot them
      # so normally, the legend will be inverted as well, but if we invert it again, you should get what you want
      df[df.columns[::-1]].plot(linewidth=10, legend="reverse")
      

      请注意,在此示例中,您不会更改数据的顺序,只是以不同的方式读取它,所以我真的不知道这是否是您想要的。

      您也可以通过创建相应的方法来让眼睛更轻松。

      def plot_dataframe(df: pd.DataFrame) -> None:
        df[df.columns[::-1]].plot(linewidth=10, legend="reverse")
      
      # then you just have to call this
      df = pd.DataFrame(np.random.randint(1,10, size=(8,3)), columns=list('XYZ'))
      plot_dataframe(df)
      

      【讨论】:

      • 感谢@spacebrger,这是一个有用的解决方案,但正如你所说的,这不是我想要的——我也不知道那个传说选项,所以也谢谢你!
      猜你喜欢
      • 2021-05-12
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 2021-04-18
      相关资源
      最近更新 更多