如何使用 subplot2grid 自定义子图中的每个轴?

How can I customize each axis in a subplot with subplot2grid?

我正在 运行 使用我编写的 csv 文件进行一些测试,代码如下

import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import dates as mpl_dates

data = pd.read_csv('teste_csvread_panda.csv')
data['date'] = pd.to_datetime(data['date'])
data.sort_values('date', inplace=True)
date = data['date']
temp = data['temp']
sal = data['sal']

ax1 = plt.subplot2grid((2,1), (0,0), rowspan=1, colspan=1)
ax2 = plt.subplot2grid((2,1), (1,0), rowspan=1, colspan=1)

ax1.plot(date,temp, marker='.', label='temp')
ax1.legend(loc='upper right')
date_format = mpl_dates.DateFormatter('%b %d')
plt.gca().xaxis.set_major_formatter(date_format)

ax2.plot(date,sal, marker='.', label='sal')
ax2.legend(loc='lower left')
plt.gca().xaxis.set_major_formatter(date_format)

plt.show()

结果图 here。

我想为两个子图设置日期轴的格式,但显然它只适用于最后一个子图。我怎样才能做到这一点?

提前谢谢你。

这应该有效。您需要定义哪个轴是当前轴。我在每个情节的开头使用 plt.sca(ax) 来做到这一点。

ax1 = plt.subplot2grid((2,1), (0,0), rowspan=1, colspan=1)
ax2 = plt.subplot2grid((2,1), (1,0), rowspan=1, colspan=1)

plt.sca(ax1)
plt.plot(date,temp, marker='.', label='temp')
plt.legend(loc='upper right')
date_format = mpl_dates.DateFormatter('%b %d')
plt.gca().xaxis.set_major_formatter(date_format)

plt.sca(ax2)
plt.plot(date, sal, marker='.', label='sal')
plt.legend(loc='lower left')
plt.gca().xaxis.set_major_formatter(date_format)

plt.show()