代码之家  ›  专栏  ›  技术社区  ›  Chiefscreation

matplotlib:将条形图上的x tick标签设置为价格范围

  •  0
  • Chiefscreation  · 技术社区  · 6 年前

    在一个plot=array上有原始的容器([0,2500,5000,7500,10000,12500,15000,17500, 20000,22500,25000,27500,30000,32500,35000,37500, 40000,42500,45000,47500,50000,52500,55000,57500, 600062500 650067500775000, 80000,82500,85000,87500,90000,92500,95000,97500, 100000,102500],数据类型=int64)

    看起来像 enter image description here

    希望x tick标签以范围和价格格式显示(例如 0-2500美元 , 2500-50000美元 等等)。类似下面的内容,但每个数字前都有$符号 enter image description here

    谢谢您!

    0 回复  |  直到 6 年前
        1
  •  1
  •   Sheldore    6 年前

    我看到了和被骗的区别。由于您没有提供MCVE,所以我将使用示例数据提供一个解决方案

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    ax.hist(np.random.normal(50000, 10000, 100000), bins=bins)
    ax.set_xlim(0, 100000)
    
    fig.canvas.draw()
    labels = [i.get_text().strip('$') for i in ax.get_xticklabels()]
    new_labels = [('\${:,}' + 'to' +  '\${:,}').format(int(i), int(j)) 
                  for i, j in zip(labels[0:-1],labels[1:])]
    
    ax.set_xticklabels(new_labels, rotation=45)
    plt.show()
    

    enter image description here

        2
  •  1
  •   LoneWanderer    6 年前

    你可以用熊猫的 cut ( doc )还有努比 linspace (或任何等价物),应该可以生成间隔箱(n箱)和相应的箱标签(n-1)。你可以用$sign来丰富那些垃圾箱的标签。 另见 Label histogram by bins matplotlib

    使用Seaborn的改编示例:

    enter image description here

    # coding=utf-8
    import numpy as np
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    data = np.random.normal(5000, 1000, 1000)
    
    dataframe = pd.DataFrame(data)
    dataframe = dataframe.rename({0 : 'values'}, axis='columns')
    print(dataframe.head(3))
    print('---------------')
    cut_vals = np.linspace(start=dataframe['values'].min(),stop=dataframe['values'].max(),num=8)
    bin_headers = list()
    
    for index in range(len(cut_vals) - 1):
        header = '$ {}-{}'.format(int(cut_vals[index]), int(cut_vals[index+1]))
        bin_headers.append(header)
    
    print(bin_headers)
    
    print('---------------')
    dataframe['categories'] = pd.cut(dataframe['values'], cut_vals, labels=bin_headers)
    
    print('---------------')
    print(dataframe.head(2))
    
    ind = np.array(cut_vals[:-1])
    width = np.array([cut_vals[i+1]-cut_vals[i] for i in range(len(cut_vals)-1)])
    
    g = sns.distplot(dataframe['values'], bins=cut_vals, label='foo')
    g.set_xticks(ind + width/2)
    g.set_xticklabels(bin_headers, rotation=45)
    plt.show()
    

    输出:

            values
    0  4442.338053
    1  5253.443608
    2  6552.700087
    ---------------
    ['$ 2080-3034', '$ 3034-3988', '$ 3988-4942', '$ 4942-5897', '$ 5897-6851', '$ 6851-7805', '$ 7805-8759']
    ---------------
    ---------------
            values   categories
    0  4442.338053  $ 3988-4942
    1  5253.443608  $ 4942-5897