【问题标题】:Datetime objects not showing correct in bar plot日期时间对象在条形图中显示不正确
【发布时间】:2014-06-27 02:06:45
【问题描述】:

我尝试阅读有关此的内容,我想我可能已经解决了我的问题,但话又说回来,它并没有按照我希望的方式工作。

我有一个名为 Year 的列表,年份从 1945 年到 2014 年;它包含如下年份:

['1945', '1946', '1946', '1947', '1947', ...] # yes, some are the same.

我已将这些转换为datetime(使用datetime.datetime.strptime(item, '%Y')),因此我可以在我的条形图中使用它们:

[datetime.datetime(1921, 1, 1, 0, 0), datetime.datetime(1925, 1, 1, 0, 0), ...]

如果我随后将我的datetime_year 绘制为 x 轴,它应该显示从 1945 年到 2014 年的年份。

当我绘制这些并尝试显示该图时,在 1921 到 2014 年的 X 轴上没有任何内容,这可能应该是什么?

相反,我在 710000 上得到了一些东西。

我的情节代码:

from matplotlib import pylab as plt
import numpy as np

plt.bar(datetime_year, sorted_ratings2)
plt.suptitle('Ratings based on years', fontsize=14)
plt.ylabel('Rating', fontsize=12)
plt.xlabel('Year', fontsize=12)  
plt.show()

还有我的情节图片:

【问题讨论】:

  • 当我绘制它时,它没有显示正确
  • 那么它的作用是什么?目前尚不清楚您的问题是什么。如果列表中有 1921,为什么要从 1945 开始?
  • 无关:datetime_years = [datetime(int(year), 1, 1) for year in Year]
  • 我已经展示了我的绘图代码,看看。
  • 看看plot_date函数。

标签: python python-2.7 datetime matplotlib


【解决方案1】:

您的代码按原样运行:

from datetime import datetime
from matplotlib import pylab as plt
import numpy as np

Year = map(str, np.random.randint(1945, 2014, size=400)) # <-- put your data here
x = np.array([datetime(int(year), 1, 1) for year in Year]) 
y = np.random.random(x.shape) # <-- put your data here

plt.bar(x, y)
plt.suptitle('Ratings based on years', fontsize=14)
plt.ylabel('Rating', fontsize=12)
plt.xlabel('Year', fontsize=12)  
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2012-12-05
    • 2017-11-24
    • 1970-01-01
    相关资源
    最近更新 更多