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

问题描述 投票:0回答:1

我正在使用以下代码对我组成的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

我想为两个子图设置日期轴的格式,但显然,它仅适用于最后一个子图。我该如何做到这一点?

谢谢你。

python axis date-formatting subplot
1个回答
0
投票

这应该有效。您需要定义哪个轴是当前轴。我使用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()
© www.soinside.com 2019 - 2024. All rights reserved.