【问题标题】:matplotlib centered bar chart with dates带日期的 matplotlib 居中条形图
【发布时间】:2012-05-04 00:27:56
【问题描述】:

要获取 x 轴为日期的条形,我正在执行以下操作:

import numpy as np
import matplotlib.pyplot as plt
import datetime

x = [datetime.datetime(2010, 12, 1, 0, 0),
    datetime.datetime(2011, 1, 1, 0, 0),
    datetime.datetime(2011, 5, 1, 1, 0)]
y = [4, 9, 2]

ax = plt.subplot(111)
barWidth=20
ax.bar(x, y, width=barWidth)
ax.xaxis_date()

plt.show()

但是,这些图并不以 x 为中心。如果之前使用 ax.bar(x-barWidth/2.,y,width=barWidth) 来获取以 x 为中心的 bar。当 x 轴值是日期时,有没有办法得到相同的结果?

【问题讨论】:

    标签: python datetime matplotlib


    【解决方案1】:

    我认为您希望 align='center' 关键字用于 bar 方法。

    对您的示例的细微更改:

    import numpy as np
    import matplotlib.pyplot as plt
    import datetime
    
    x = [datetime.datetime(2010, 12, 1, 0, 0),
        datetime.datetime(2011, 1, 1, 0, 0),
        datetime.datetime(2011, 5, 1, 1, 0)]
    y = [4, 9, 2]
    
    ax = plt.subplot(111)
    barWidth=20
    ax.bar(x, y, width=barWidth, align='center') #< added align keyword
    ax.xaxis_date()
    
    plt.savefig('baralign.png')
    plt.show()
    

    引出下图:

    如果您知道在哪里看,这是一个非常直接的答案。 matplotlib 有大量文档,开发人员为每种绘图方法提供了a detailed description of the keyword arguments

    【讨论】:

    • 完美。不知怎的,我错过了它。非常感谢。
    猜你喜欢
    • 2011-08-19
    • 2021-05-23
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多