在x轴上具有日期的不连续时间序列图 [英] Discontinuous timeseries plot with dates on x-axis

查看:375
本文介绍了在x轴上具有日期的不连续时间序列图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经获得了几个月的数据,但是在几个月之间却丢失了.如果将整个数据集绘制在一个图中(中间有很多空白),这看起来很奇怪. 我写了一个小示例脚本来演示其工作原理(基于:

I got data for several months, but in between some months are missing. This looks quite strange if I plot the whole dataset in one plot (lots of empty space in between). I wrote the small example script to show how it works (based on: Python/Matplotlib - Is there a way to make a discontinuous axis?)

问题:我无法让X轴使用相同的日期格式!斧头或斧头2是正确的,但都不是两者都正确. 你有什么主意吗?

The problem: I can't get the x-axis use the same date formatting! Either ax or ax2 is correct, but never both of them. Do you have any idea?

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

def getDates(startdate, enddate):
    days  = (enddate + datetime.timedelta(days=1) - startdate).days
    dates = [ startdate + datetime.timedelta(days=x) for x in range(0,days) ]
    return dates

dates1 = getDates(datetime.datetime(2013,1,1), datetime.datetime(2013,1,31))
dates2 = getDates(datetime.datetime(2013,3,1), datetime.datetime(2013,3,31))
dates = dates1+dates2
data = np.arange(len(dates))

Locator = mpl.dates.DayLocator(interval=5)
Formatter = mpl.dates.DateFormatter('%d-%m-%y')

fig,(ax,ax2) = plt.subplots(1,2,sharey=True)
fig.subplots_adjust(wspace=0.05)
fig.set_size_inches(10,3)
ax.plot(dates, data)
ax2.plot(dates, data)
ax.legend(loc=1)
ax.set_ylim( 0, 61 )
ax.set_xlim( datetime.datetime(2013,1,1), datetime.datetime(2013,1,31) )
ax2.set_xlim( datetime.datetime(2013,3,1), datetime.datetime(2013,3,31) )
labels = ax.get_xticklabels()
for label in labels: label.set_rotation(30)
labels = ax2.get_xticklabels()
for label in labels: label.set_rotation(30) 
ax.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax.tick_params(right='off')
ax2.tick_params(left='off')
ax2.yaxis.tick_right()
ax.xaxis.set_major_locator(Locator)
ax.xaxis.set_major_formatter(Formatter)
ax2.xaxis.set_major_locator(Locator)
ax2.xaxis.set_major_formatter(Formatter)
plt.savefig("test.png", bbox_inches='tight')

结果:

推荐答案

您已经找到了有关matplotlib内部的有趣细节.传递到set_major_locator 的locator对象是轴所使用的对象,用于确定将axes的刻度线放置在哪里,这两个axes都使用相同的定位器对象.作为绘制的一部分,定位器会基于轴的限制生成应在哪里打勾的列表,当第二个轴完成时,这意味着在第一个轴上看不到任何打勾.您只需要传递不同的(单独的实例化)定位器对象,即可在此处使用copy完成.

You have found an interesting detail about the internals of matplotlib. The locator object you pass into set_major_locator is the object used by the axes to figure out where to put it's ticks both axes were using the same locater object. As part of the draw the locator generates a list of where the ticks should be based on the limits of the axes which when it gets done for the second axes means no ticks are visible in the first axes. You just need to pass in distinct (separate instantiations) locator objects, done here with copy.

import datetime
import copy

def getDates(startdate, enddate):
    days  = (enddate + datetime.timedelta(days=1) - startdate).days
    dates = [ startdate + datetime.timedelta(days=x) for x in range(0, days) ]
    return dates

dates1 = getDates(datetime.datetime(2013, 1, 1), datetime.datetime(2013, 1, 31))
dates2 = getDates(datetime.datetime(2013, 3, 1), datetime.datetime(2013, 3, 31))
dates = dates1+dates2
data = np.arange(len(dates))

Locator = mpl.dates.DayLocator(interval=5)
Formatter = mpl.dates.DateFormatter('%d-%m-%y')

fig, (ax, ax2) = plt.subplots(1, 2, sharey=True, tight_layout=True)
fig.subplots_adjust(wspace=0.05)
fig.set_size_inches(10, 3, forward=True)

ax.plot(dates, data)
ax2.plot(dates, data)

ax.legend(loc=1)
ax.set_ylim(0, 61)
ax.set_xlim(datetime.datetime(2013, 1, 1), datetime.datetime(2013, 1, 31))
ax2.set_xlim(datetime.datetime(2013, 3, 1), datetime.datetime(2013, 3, 31))

labels = ax.get_xticklabels()
for label in labels:
    label.set_rotation(30)
labels = ax2.get_xticklabels()
for label in labels:
    label.set_rotation(30)

ax.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax.tick_params(right='off')
ax2.tick_params(left='off')
ax2.yaxis.tick_right()


# note the copy here
ax.xaxis.set_major_locator(copy.copy(Locator))
ax.xaxis.set_major_formatter(copy.copy(Formatter))
ax2.xaxis.set_major_locator(copy.copy(Locator))
ax2.xaxis.set_major_formatter(copy.copy(Formatter))

这篇关于在x轴上具有日期的不连续时间序列图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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