代码之家  ›  专栏  ›  技术社区  ›  Matt W.

使用x轴上的标签(而不是计数)打印直方图matplotlib

  •  2
  • Matt W.  · 技术社区  · 8 年前

    我想用 value_counts() 或者类似的python语言。我的数据如下所示:

    Lannister                      8
    Stark                          8
    Greyjoy                        7
    Baratheon                      6
    Frey                           2
    Bolton                         2
    Bracken                        1
    Brave Companions               1
    Darry                          1
    Brotherhood without Banners    1
    Free folk                      1
    Name: attacker_1, dtype: int64
    

    您可以使用任何可复制的代码,如:

    pd.DataFrame({'Family':['Lannister', 'Stark'], 'Battles':[6, 8]})
    

    我正在使用

    plt.hist(battles.attacker_1.value_counts())
    

    histogram

    我希望x轴显示家族的名字,而不是战斗的次数,我希望战斗的次数是柱状图。我试着只使用一系列的姓氏(Lannister重复了8次),而不是使用 value\u counts() 我想这可能行得通,但我不知道还能怎么做。

    3 回复  |  直到 8 年前
        1
  •  3
  •   Matt W.    8 年前

    找到了答案。

    battles.attacker_1.value_counts().plot(kind = 'bar')
    
        2
  •  2
  •   jrd1    8 年前

    对于 香草matplotlib 解决方案,使用 xticklabels 具有 xticks :

    import random
    import matplotlib.pyplot as plt
    
    
    NUM_FAMILIES = 10
    
    # set the random seed (for reproducibility)
    random.seed(42)
    
    # setup the plot
    fig, ax = plt.subplots()
    
    # generate some random data
    x = [random.randint(0, 5) for x in range(NUM_FAMILIES)]
    
    # create the histogram
    ax.hist(x, align='left') # `align='left'` is used to center the labels
    
    # now, define the ticks (i.e. locations where the labels will be plotted)
    xticks = [i for i in range(NUM_FAMILIES)]
    
    # also define the labels we'll use (note this MUST have the same size as `xticks`!)
    xtick_labels = ['Family-%d' % (f+1) for f in range(NUM_FAMILIES)]
    
    # add the ticks and labels to the plot
    ax.set_xticks(xticks)
    ax.set_xticklabels(xtick_labels)
    
    plt.show()
    

    这将产生:

    histogram plot

        3
  •  1
  •   BENY    8 年前

    你可以看看 pandas plot

    df.set_index('Family').Battles.plot(kind='bar')
    

    enter image description here