matplotlib中以日期为x轴的最简单直方图 [英] Simplest histogram with dates as x-axis in matplotlib

查看:60
本文介绍了matplotlib中以日期为x轴的最简单直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试正确显示一个简单的直方图,其中日期为 x 轴,整数为 y 轴.下面的示例碰巧是一个子图(2个y轴,1个共享的x轴),但问题不存在,而是历史记录本身.

I have been trying to properly display a simple histogram with dates as x-axis and integers as y-axis. The example below happens to be a subplot (2 y-axis, 1 shared x-axis) but the problem is not there, it's rather the hist itself.

import datetime
import matplotlib
matplotlib.use('agg')   # server no need to display graphics
import matplotlib.pyplot as plt

# x-axis is 3 consecutive dates (days)
now = datetime.datetime.now().date()
x = [now, now + datetime.timedelta(days=1), now + datetime.timedelta(days=2)]

# y1-axis is 3 numbers
y1 = [10, 0, 3]
y2 = [8, 0, 3]

fig, axarr = plt.subplots(2, sharex=True)
bins = range(1, len(x) + 1)
axarr[1].hist(y1, bins=len(x), edgecolor="k")
axarr[1].set_xticks(bins)
axarr[1].set_xticklabels(x)
axarr[1].set_yticks(range(0, max(y1) + 1))

# axarr[0] ommitted for simplicity

plt.savefig('a.png', bbox_inches='tight')

但是我得到的图像是......

However the image I get is ...

推荐答案

您可能想要一个 bar 图.

You probably want a bar graph.

import datetime
import matplotlib
matplotlib.use('agg')   # server no need to display graphics
import matplotlib.pyplot as plt

# x-axis is 3 consecutive dates (days)
now = datetime.datetime.now().date()
x = [now, now + datetime.timedelta(days=1), now + datetime.timedelta(days=2)]

# y1-axis is 3 numbers
y1 = [10, 0, 3]
y2 = [8, 0, 3]

fig, axarr = plt.subplots(2, sharex=True)
bins = range(1, len(x) + 1)
axarr[1].bar(x, y1, edgecolor="k")
axarr[1].set_xticks(x)
axarr[1].set_xticklabels(x)

plt.savefig('a.png', bbox_inches='tight')

这篇关于matplotlib中以日期为x轴的最简单直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆