【问题标题】:Change matplotlib.bar Order in python 2.7 [duplicate]在 python 2.7 中更改 matplotlib.bar 顺序 [重复]
【发布时间】:2018-05-23 16:46:22
【问题描述】:

在这个例子中:

import matplotlib.pyplot as plt

colors = ['white', 'orange', 'green', 'purple']
rates = ['5','5','4','3']

plt.bar(colors, rates)

图中的条形按字母顺序排列。

如何让它们以与代码中相同的顺序显示(从最高到最低的比率)?

【问题讨论】:

    标签: python matplotlib plot anaconda histogram


    【解决方案1】:

    将值0,1,2,3,4,... 用作x 并将colors 分配给tick_label=

    import matplotlib.pyplot as plt
    
    colors = ['white', 'orange', 'green', 'purple']
    rates = ['5','5','4','3']
    
    plt.bar(range(len(colors)), rates, tick_label=colors)
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      Matplotlib 2.1 为 use strings as input to its plotting functions 提供了新选项 - 称为“分类”。这是一项新功能,尚未完全正常工作。一个警告是字符串是自动排序的(按字母顺序)。此限制为removed in the next release

      在此之前,您将像在 matplotlib 甚至不允许输入字符串时一样生成绘图。将数据转换为数字,并根据列表索引进行绘图。然后将刻度标签设置为他们的名字。

      import matplotlib.pyplot as plt
      
      colors = ['white', 'orange', 'green', 'purple']
      rates = ['5','5','4','3']
      
      plt.bar(range(len(colors)), list(map(float,rates)) )
      plt.xticks(range(len(colors)), colors)
      
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        相关资源
        最近更新 更多