【问题标题】:Python - Changing Matplotlib Axis from Days to YearsPython - 将 Matplotlib 轴从几天更改为几年
【发布时间】:2015-11-04 02:55:09
【问题描述】:

我正在尝试在 Python 中使用 Pandas 和 Matplotlib 来绘制多年来收到的赠款总额。数据类型“奖励生效日期”是收到赠款的日期。我用以下代码总结了多年来收到的赠款每天的金额:

    #Displays daily sums of awards from FY12 to FY16
    # *Revise ledger so only FY year dates are reported, not days.

    df.groupby('Award Effective Date').award_amount.sum().plot(kind='bar',color=['orange'],\
                                                           figsize=(25,10),title="Daily Sums of Awards FY12 to FY16",\
                                                          grid=True)

这绘制了我需要的内容,但 x 轴标签混乱且难以辨认,因为它在过去几年中每天都在读取。如何将其更改为仅读取年份而不是每天?我还有另一种名为“EffDate 的财政年度”的数据类型,它记录该日期的财政年度——如果可以使用的话。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    这样的事情怎么样?需要根据您的具体情况进行修改...

    import matplotlib.pyplot as plt
    
    x = range(0,1000)
    y = [i*2 for i in x]
    
    plt.plot(x,y)
    
    x_ticks = [day for day in x if day%365 == 0] # Only pull out full years
    x_labels = ['Year ' + str(i) for i in range(len(x_ticks))]
    
    plt.xticks(x_ticks, x_labels)
    plt.show()
    

    这情节: years.py

    【讨论】:

    • 想了想,其实需要轴从“FY of EffDate”数据类型中读取。如果我只是尝试按照您所说的进行设置,则它不会在财政年度中读取,而是在日历年度中读取。
    • 代替我定义的x_ticks,您可以创建一个短循环来查找您所有日子的FY,然后遍历它寻找唯一值。每次您找到一个唯一值时,将当天添加到您的x_ticks 并将适当的字符串添加到x_labels。如果您更喜欢将标签放在年中:您可以使用x_ticks.append(unique_day + 182),假设您的年份大约为 2*182 天。请注意,您输入到 plt.xticks()x_ticks 必须以天为单位(因为这就是您的原始数据的定义)。
    猜你喜欢
    • 2021-08-15
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多