[英]How can I customize each axis in a subplot with subplot2grid?
I'm running some tests with a csv file I made up, with the following code我正在使用我编写的 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()
resulting plot here .在这里得到 plot 。
I would like to format the date axis for both subplots, but clearly it's working only for the last subplot.我想为两个子图格式化日期轴,但显然它只适用于最后一个子图。 How can I make this happen?我怎样才能做到这一点?
Thank you in advance.先感谢您。
This should work.这应该有效。 You need to define which axis is the current axis.您需要定义哪个轴是当前轴。 I used plt.sca(ax)
to do that at the beginning of each plot.我在每个 plot 的开头使用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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.