Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Matplotlib子批次日期时间X轴刻度未按预期工作_Python_Datetime_Matplotlib_Plot - Fatal编程技术网

Python Matplotlib子批次日期时间X轴刻度未按预期工作

Python Matplotlib子批次日期时间X轴刻度未按预期工作,python,datetime,matplotlib,plot,Python,Datetime,Matplotlib,Plot,我试图绘制许多图,以下是数据组织方式的示例: 我的意图是使用谷歌分析数据,为数小时或数天(比如一周7天,或一天24小时)构建一系列子地块。我的索引是日期时间对象 下面是一个例子,说明了当轴正确完成时,单个绘图的外观 from datetime import datetime, date, timedelta import matplotlib.pyplot as plt import numpy as np import seaborn as sns import matplotlib.dat

我试图绘制许多图,以下是数据组织方式的示例:

我的意图是使用谷歌分析数据,为数小时或数天(比如一周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()

如您所见,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
然而,这就产生了下面非常古怪的图,轴的标签错误:

我尝试添加一行,看看它是否因为垂直空间而被遮盖:

但是当遇到同样的行为时,只有最后一个子地块的轴在工作,其余的不工作


如有任何见解,将不胜感激

因此,答案是几年前提出的与
set\u major\u locator()
set\u major\u formatter()对象相关的以下github问题:

引用埃里克的话:

您遗漏了一些内容,但这是一个非常不直观且容易遗漏的内容:定位器不能在轴之间共享。set_major_locator()方法将其轴指定给该定位器,覆盖以前指定的任何轴

因此,解决方案是为每个新轴实例化一个新的
dates.MinuteLocator
dates.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和dates.Formatter对象,所以可以使用相同的名称重新实例化每个循环。(但我可能错了!)

我也有同样的子批次datetime x轴记号缺失问题。下面的代码与OP的代码非常相似,似乎可以正常工作,请参见附图。但是,我使用的是matplotlib 3.1.0,这个版本可能已经解决了这个问题?但我有一个观察:如果我为第二个子批次启用
fig.autofmt_xdate()
,第一个子批次的日期时间x轴将不会显示

fig = plt.figure()
plt.rcParams['figure.figsize'] = (width, height)
plt.subplots_adjust(wspace=0.25, hspace=0.2)

ax = fig.add_subplot(2,1,1)
ax.xaxis.set_major_locator(MonthLocator(bymonthday=1))
ax.xaxis.set_major_formatter(DateFormatter('%Y-%b'))
ax.plot(df1['DATE'], df1['Movement'], '-')
plt.ylabel(r'$D$', fontsize=18)
plt.xticks(fontsize=12)
plt.yticks(fontsize=16)
plt.legend(fontsize=16, frameon=False)
fig.autofmt_xdate()

ax = fig.add_subplot(2,1,2)
ax.xaxis.set_major_locator(MonthLocator(bymonthday=1))
ax.xaxis.set_major_formatter(DateFormatter('%Y-%b'))
ax.plot(df2['DATE'], df2['Movement'], '-')
#plt.ylabel(r'$D`enter code here`$', fontsize=18)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.legend(fontsize=16, frameon=False)
#fig.autofmt_xdate()

plt.show()