Axis 中的子图日期格式

Subplot date formatting in Axis

我有一个 2x2 图表,两个图表的 x 轴上都有日期。我已经使用 datetime.strptimestring 转换为 type = datetime.datetime 对象格式。

但是我计划有大约 12 个子图并且按照以下方式执行此操作似乎很混乱。

有更好的'pythonic'方法吗?

这是我的:

 xx.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
 plt.grid(True)
 plt.ylabel('paramA',fontsize=8, color = "blue")
 plt.tick_params(axis='both', which='major', labelsize=8)
 plt.plot(date_list, myarray[:,0], '-b', label='paramA')
 plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment

 xx = plt.subplot(2,1,2)
 xx.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
 plt.grid(True)
 plt.ylabel('paramB', 'amount of virtual mem',fontsize=8, color = "blue")
 plt.tick_params(axis='both', which='major', labelsize=8)
 plt.plot(date_list, myarray[:,1], '-y', label='paramB')plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment ```

PS:最初我尝试按如下方式定义情节。然而,这没有用:

fig, axs = plt.subplots(2,1,figsize=(15,15)) 
plt.title('My graph')     
for ax in enumerate(axs):
   ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M:%S'))

您未能提供任何数据或Minimal, Complete, and Verifiable example。尽管如此,这样的事情应该有效。您可以通过在第一个命令中使用所需的行数和列数来将其扩展到您的实际情况。

fig, axes = plt.subplots(nrows=2, ncols=3)
labels = ['paramA', 'paramB', 'paramC', 'paramD', 'paramE', 'paramF']

for i, ax in enumerate(axes.flatten()):
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
    ax.grid(True)
    ax.set_ylabel(labels[i], fontsize=8, color="blue")
    ax.tick_params(axis='both', which='major', labelsize=8)
    ax.plot(date_list, myarray[:,i], '-b', label=labels[i])
    plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment

编辑:

将您的代码更改为

fig, axs = plt.subplots(2,1,figsize=(15,15)) 
plt.title('My graph')     
for ax in axs:
   ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M:%S'))