2016-03-10 76 views
1

我试图绘制许多情节,这里的数据是如何组织的样本:Matplotlib插曲日期时间X轴蜱未如预期运行

dataframe

我的目的是要建立一系列的使用谷歌分析数据的小时数或天数(例如一周7天,或一天24小时)。我的索引是日期时间对象。

下面是一个示例,说明当轴正确完成时单个绘图的外观。

from datetime import datetime, date, timedelta 
import matplotlib.pyplot as plt 
import numpy as np 
import seaborn as sns 
import matplotlib.dates as dates 

#creating our graph and declaring our locator/formatters used in axis labelling. 
hours = dates.HourLocator(interval=2) 
hours_ = dates.DateFormatter('%I %p') 

el = datetime(year=2016, day=1, month=3, hour=0) 
fig, ax = plt.subplots(ncols = 1, nrows= 1) 
fig.set_size_inches(18.5, 10.5) 
fig.tight_layout() 
ax.set_title(el.strftime('%a, %m/%d/%y')) 
ax.plot(df_total.loc[el:el+timedelta(hours=23, minutes=59),:].index, 
          df_total.loc[el:el+timedelta(hours=23, minutes=59),:].hits, '-') 
ax.xaxis.set_major_locator(hours) 
ax.xaxis.set_major_formatter(hours_) 
fig.show() 

right graph!

正如你所看到的,x轴看起来不错,如预期运行与正确的蜱/日期标签。

但是,当我尝试在子系列图上运行同一个图时,我遇到以下错误。这里是我的代码:

fig, ax = plt.subplots(ncols = 3, nrows= 2) 
fig.set_size_inches(18.5, 10.5) 
fig.tight_layout() 

nrows=2 
ncols=3 

count = 0 

for row in range(nrows): 
    for column in range(ncols): 
     el = cleaned_date_range[count] 
     ax[row][column].set_title(el.strftime('%a, %m/%d/%y')) 
     ax[row][column].xaxis.set_major_locator(hours) 
     ax[row][column].xaxis.set_major_formatter(hours_) 
     ax[row][column].plot(df_total.loc[el:el+timedelta(hours=23,minutes=59),:].index, df_total.loc[el:el+timedelta(hours=23,minutes=59),:].hits) 
     count += 1 

     if count == 7: 
      break 

然而,得到下面的非常时髦的情节,与贴错标签的轴:

wrong graph!

我增加一个额外的行实验,看它是否只是掩饰,因为垂直空间: enter image description here

但面临相同的行为,只有最后一个子图的轴似乎与其他工作不工作。

任何有识之士将不胜感激!

回答

2

所以答案在下面GitHub的问题提出了数年前相关set_major_locator()set_major_formatter()对象:

https://github.com/matplotlib/matplotlib/issues/1086/

引述埃里克:

“你失去了一些东西,但这是非常不直观和容易遗漏的事情:定位器不能在轴之间共享,set_major_locator()方法将其轴指定给该定位器,覆盖之前分配的任何轴。“

所以解决的办法就是实例化一个新dates.MinuteLocatordates.DateFormatter对象为每个新的轴,如:

for ax in list_of_axes: 
    minutes = dates.MinuteLocator(interval=5) 
    minutes_ = dates.DateFormatter('%I:%M %p') 
    ax.xaxis.set_major_locator(minutes) 
    ax.xaxis.set_major_formatter(minutes_) 

我已经试验,它看起来像你不需要引用dates.Locator和date.Formatter对象之后,因此可以使用相同名称对每个循环重新实例化。 (虽然我可能在这里错了!)