【问题标题】:How can I customize each axis in a subplot with subplot2grid?如何使用 subplot2grid 自定义子图中的每个轴?
【发布时间】:2019-10-31 22:34:08
【问题描述】:

我正在使用我制作的 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】:

    这应该可行。您需要定义哪个轴是当前轴。我在每个情节的开头使用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()
    

    【讨论】:

    • @ThiagoCaminha 能否请acceptupvote 回答?谢谢。
    猜你喜欢
    • 2017-05-07
    • 2020-10-08
    • 2018-10-07
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多