【问题标题】:Pandas dataframe columns sorted while plottingPandas 数据框列在绘图时排序
【发布时间】:2017-06-15 01:31:00
【问题描述】:

我有一个包含多个列的 pandas 数据框,如下所示:

columns_all = pd.DataFrame({'m1_h':m1_hist, 'm2_h':m2_hist, ....... 'm6_h':m6_hist, 'm6_f':m6_futu})

我使用以下基于每列绘制直方图,但列已排序但我希望所有直方图的顺序与上述数据框中写入的列的顺序相同:

columns_all.hist(layout=(2,6), sharey=True, sharex=True)
plt.ylim(0, 100)
plt.xlim(0, 150)
plt.show()

感谢在绘图时保持列顺序的任何建议。

【问题讨论】:

    标签: python pandas matplotlib histogram


    【解决方案1】:

    根据the source code,排序由_try_sort(data.columns) 定义,不能通过参数更改。你可以做什么Claudiu Creanga suggested。但是,在我的测试中,这不会为您提供 (2, 6) 布局。如果您真的想要该布局以及 pandas.DataFrame.hist 的功能,以下代码可能会有所帮助:

    from matplotlib import pyplot as plt
    import numpy as np
    import pandas as pd
    
    columns_all = pd.DataFrame([np.random.randn(1000)] * 7).T
    columns_all.columns = ['m1_h', 'm2_h', 'm3_h', 'm4_h', 'm5_h', 'm6_h', 'm6_f']
    plt.clf()
    fig = plt.figure(figsize=(16, 4))
    axarr = []
    for i, col in enumerate(columns_all.columns):
        if i // 6 > 0:
            sharex = axarr[i % 6]
            plt.setp(axarr[i % 6].get_xticklabels(), visible=False)
        else:
            sharex = None
        if i % 6 > 0:
            sharey = axarr[i // 6]
        else:
            sharey = None
        ax = fig.add_subplot(2, 6, i + 1, sharex=sharex, sharey=sharey)
        axarr.append(ax)
        if i % 6 > 0:
            plt.setp(ax.get_yticklabels(), visible=False)
        ax.hist(columns_all[col].dropna().values)
        ax.set_title(col)
        ax.grid(True)
    fig.subplots_adjust(wspace=0.3, hspace=0.3)
    plt.show()
    

    【讨论】:

      【解决方案2】:

      您可以重复调用各个列,因为在创建数据框和 .hist() 时都会自动进行重新排序:

      s = pd.DataFrame([{'B': 1.5, 'A':3, 'C': 4, 'D':2}])
      s
      
          A   B   C   D
      0   3   1.5 4   2
      
      s = s[["B", "A", "C", "D"]] #chose your order
      s
      
          B   A   C   D
      0   1.5 3   4   2
      
      for x in s.columns:
          s[[x]].hist(layout=(2,6), sharey=True, sharex=True)
      plt.ylim(0, 100)
      plt.xlim(0, 150)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-07-26
        • 2017-08-02
        • 1970-01-01
        • 2017-12-26
        • 1970-01-01
        • 2020-02-29
        • 2019-06-18
        相关资源
        最近更新 更多