使用matplotlib.pyplot.plot_date的子图


import numpy as np
import pandas as pan
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import csv 
import datetime 
timestamp1 = []
for t in ts_temp1:
timestamp1.append(mdates.datestr2num(t))
formatter = mdates.DateFormatter('%Y-%b-%d')
plt.plot_date(timestamp1,xgtemp1,'r.',label='X GALVO 1',lw=2)
plt.plot_date(timestamp1,ygtemp1,'b.',label='Y GALVO 1',lw=2)
ax = plt.gcf().axes[0] 
ax.xaxis.set_major_formatter(formatter)
plt.gcf().autofmt_xdate(rotation=25)
plt.ylabel('Galvo Temperatures (°C)')
plt.grid()
plt.legend(loc='upper right')
plt.show()

我正在尝试创建一个包含 3 行和 1 列图的子图。 我有 3 个与上述代码相同的"绘图"代码块。 目标是使子图中的所有图共享相同的 x 轴。 我不确定如何处理这个子情节,因为我以前的许多尝试都没有奏效。

旁注:我尝试过用其他方法绘制,但这是唯一一种正确绘制时间戳的方法。

尝试使用:

fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True)
ax1.plot_date(timestamp1,xgtemp1,'r.',label='X GALVO 1',lw=2)
ax1.plot_date(timestamp1,ygtemp1,'b.',label='Y GALVO 1',lw=2)
ax1.xaxis.set_major_formatter(formatter)
fig.autofmt_xdate(rotation=25)
ax.set_ylabel('Galvo Temperatures (°C)')
ax.grid()
ax.legend(loc='upper right')
fig.show()

我认为最好直接使用Axes对象(ax1ax2ax3),而不是让 pyplot 来弄清楚它或提取当前AxesFigure对象。对于其他子图,请使用ax2ax3或改为执行以下操作:

fig, axn = plt.subplots(3, 1, sharex=True)

并循环axn.

此外,如果您仍然使用 pandas,您可以将plot_date命令替换为df['column'].plot(ax=ax1, lw=2)并跳过时间戳准备工作。

最新更新