且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

轴上的数据未按预期顺序

更新时间:2023-12-05 07:55:28

Matplotlib 当前(从 2.1 版开始)在轴上的类别顺序方面存在问题.它总是在绘图之前对类别进行排序,并且您没有机会更改该顺序.这有望在下一个版本中得到修复,但在那之前您需要坚持在轴上绘制数值.

Matplotlib currently (as of version 2.1) has a problem with the order of categories on the axes. It will always sort the categories prior to plotting and you have no chance of changing that order. This will hopefully be fixed for the next release, but until then you would need to stick to plotting numeric values on the axes.

在这种情况下,这意味着您将数据绘制在某个索引上,然后相应地设置刻度线.当然,您也可以使用 DateTimes,但这似乎有点矫枉过正,因为您已经有了可用月份的列表.

In this case this would mean you plot the data against some index and later set the ticklabes accordingly. Of course you could also use DateTimes, but that seems a bit overkill is you already have a list of the months available.

import numpy as np
import matplotlib.pyplot as plt


data_list = [('January', 1645480), ('February', 1608476), ('March', 1557113), 
             ('April', 1391652), ('May', 1090298), ('July', 1150535), 
             ('August', 1125931), ('September', 1158741), ('October', 1305849), 
             ('November', 1407438), ('December', 1501733)]

#### GRAPHING
def create_graph(data):
    months, y = zip(*data)
    plt.plot(range(len(months)),y)
    axes = plt.gca() # Get the Current Axes
    axes.get_yaxis().get_major_formatter().set_scientific(False)  
    axes.set_xticks(range(len(months)))
    axes.set_xticklabels(months, rotation=45, ha="right")
    # Show data on Y axis points
    for i, j in enumerate(y):
        plt.annotate(str(j),xy=(i,j))
    plt.show()


create_graph(data_list)