matplotlib 单个子图中缺少网格

qjp7pelc  于 2023-02-09  发布在  其他
关注(0)|答案(1)|浏览(120)

我使用相同的代码来创建下图中的每个子图,但我不知道为什么其中一个子图缺少网格线。

奇怪的是,我可以在事后添加网格线:

In [18]: ax2b
Out[18]: <AxesSubplot:title={'center':'12:10-12:16 (after 13:00 PST Oct 26th)'}>

In [19]: ax2b.xaxis.grid(which='major'); fig
Out[19]:

但这正是我的脚本工作的方式,所以我不明白为什么(2,2)的子情节被忽略了。
我已经尽了最大的努力来排 debugging 别字或错误。下面是脚本的情节生成(数据不包括抱歉):

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker

run5 = combine_run5_data()

pdtpst = '2022-10-26T13:00'
colname = 'Licor_CO2'
cycle1a = run5[:pdtpst].between_time('05:00', '05:35').groupby(lambda idx: idx.dayofyear)
cycle2a = run5[:pdtpst].between_time('11:00', '11:35').groupby(lambda idx: idx.dayofyear)
cycle3a = run5[:pdtpst].between_time('17:00', '17:35').groupby(lambda idx: idx.dayofyear)
cycle4a = run5[:pdtpst].between_time('23:00', '23:35').groupby(lambda idx: idx.dayofyear)
cycle1b = run5[pdtpst:].between_time('06:00', '06:35').groupby(lambda idx: idx.dayofyear)
cycle2b = run5[pdtpst:].between_time('12:00', '12:35').groupby(lambda idx: idx.dayofyear)
cycle3b = run5[pdtpst:].between_time('18:00', '18:35').groupby(lambda idx: idx.dayofyear)
cycle4b = run5[pdtpst:].between_time('00:00', '00:35').groupby(lambda idx: idx.dayofyear)
  
nrows, ncols = 4, 2
fig = plt.figure(figsize=(6*ncols,3*nrows), constrained_layout=True)
fig.suptitle('Run 5 drain cycle flagging (pink=active, blue=recovery)')
fig.supylabel('LI-COR carbon dioxide data, normalized to 0-1')
fig.supxlabel('Pacific Standard Time (UTC-0800)')
xmajor = 5 # minutes
xminor = 1  # minutes

ax1a = fig.add_subplot(nrows, ncols, 1)
ax1b = fig.add_subplot(nrows, ncols, 2)
ax2a = fig.add_subplot(nrows, ncols, 3)
ax2b = fig.add_subplot(nrows, ncols, 4)
ax3a = fig.add_subplot(nrows, ncols, 5)
ax3b = fig.add_subplot(nrows, ncols, 6)    
ax4a = fig.add_subplot(nrows, ncols, 7)
ax4b = fig.add_subplot(nrows, ncols, 8)

for doy, grp in cycle1a:
    grp.index -= grp.index.floor('D')
    data = grp[colname] / max(grp[colname])
    
    ax1a.plot(data.index, data)
    ax1a.set_title('5:10-5:16 (before 13:00 PST Oct 26th)')
    ax1a.set_xlim(min(data.index).value, max(data.index).value)
    ax1a.yaxis.grid(which='major')
    ax1a.xaxis.grid(which='both')
    ax1a.xaxis.set_major_locator(ticker.MultipleLocator(1e9*60*xmajor))
    ax1a.xaxis.set_minor_locator(ticker.MultipleLocator(1e9*60*xminor))
    ax1a.xaxis.set_major_formatter(lambda x,p: pd.Timestamp(x).strftime('%H:%M'))
    ax1a.axvspan(pd.Timedelta('05:10:00').value, # HINT requires hh:mm:ss format
                 pd.Timedelta('05:16:00').value,
                 alpha=0.5, 
                 color='pink')
    ax1a.axvspan(pd.Timedelta('05:16:00').value,
                 pd.Timedelta('05:22:00').value,
                 alpha=0.8, 
                 color='skyblue')

for doy, grp in cycle1b:
    grp.index -= grp.index.floor('D')
    data = grp[colname] / max(grp[colname])
    
    ax1b.plot(data.index, data)
    ax1b.set_title('6:10-6:16 (after 13:00 PST Oct 26th)')
    ax1b.set_xlim(min(data.index).value, max(data.index).value)
    ax1b.yaxis.grid(which='major')
    ax1b.xaxis.grid(which='both')
    ax1b.xaxis.set_major_locator(ticker.MultipleLocator(1e9*60*xmajor))
    ax1b.xaxis.set_minor_locator(ticker.MultipleLocator(1e9*60*xminor))
    ax1b.xaxis.set_major_formatter(lambda x,p: pd.Timestamp(x).strftime('%H:%M'))
    ax1b.axvspan(pd.Timedelta('06:10:00').value, # HINT requires hh:mm:ss format
                 pd.Timedelta('06:16:00').value,
                 alpha=0.5, 
                 color='pink')
    ax1b.axvspan(pd.Timedelta('06:16:00').value,
                 pd.Timedelta('06:22:00').value,
                 alpha=0.8, 
                 color='skyblue')
    
for doy, grp in cycle2a:
    grp.index -= grp.index.floor('D')
    data = grp[colname] / max(grp[colname])
    
    ax2a.plot(data.index, data)
    ax2a.set_title('11:10-11:16 (before 13:00 PST Oct 26th)')
    ax2a.set_xlim(min(data.index).value, max(data.index).value)
    ax2a.yaxis.grid(which='major')
    ax2a.xaxis.grid(which='both')
    ax2a.xaxis.set_major_locator(ticker.MultipleLocator(1e9*60*xmajor))
    ax2a.xaxis.set_minor_locator(ticker.MultipleLocator(1e9*60*xminor))
    ax2a.xaxis.set_major_formatter(lambda x,p: pd.Timestamp(x).strftime('%H:%M'))
    ax2a.axvspan(pd.Timedelta('11:10:00').value, # HINT requires hh:mm:ss format
                 pd.Timedelta('11:16:00').value,
                 alpha=0.5, 
                 color='pink')
    ax2a.axvspan(pd.Timedelta('11:16:00').value,
                 pd.Timedelta('11:22:00').value,
                 alpha=0.8, 
                 color='skyblue')

#### XXXX this one doesn't plot correctly ###############
for doy, grp in cycle2b:    
    grp.index -= grp.index.floor('D')
    data = grp[colname] / max(grp[colname])
    
    ax2b.plot(data.index, data)
    ax2b.set_title('12:10-12:16 (after 13:00 PST Oct 26th)')
    ax2b.set_xlim(min(data.index).value, max(data.index).value)
    ax2b.yaxis.grid(which='major')
    ax2b.xaxis.grid(which='both')
    ax2b.xaxis.set_major_locator(ticker.MultipleLocator(1e9*60*xmajor))
    ax2b.xaxis.set_minor_locator(ticker.MultipleLocator(1e9*60*xminor))
    ax2b.xaxis.set_major_formatter(lambda x,p: pd.Timestamp(x).strftime('%H:%M'))
    ax2b.axvspan(pd.Timedelta('12:10:00').value, # HINT requires hh:mm:ss format
                 pd.Timedelta('12:16:00').value,
                 alpha=0.5, 
                 color='pink')
    ax2b.axvspan(pd.Timedelta('12:16:00').value,
                 pd.Timedelta('12:22:00').value,
                 alpha=0.8, 
                 color='skyblue')
##########################################################
    
for doy, grp in cycle3a:
    grp.index -= grp.index.floor('D')
    data = grp[colname] / max(grp[colname])
    
    ax3a.plot(data.index, data)
    ax3a.set_title('17:10-17:16 (before 13:00 PST Oct 26th)')
    ax3a.set_xlim(min(data.index).value, max(data.index).value)
    ax3a.yaxis.grid(which='major')
    ax3a.xaxis.grid(which='both')
    ax3a.xaxis.set_major_locator(ticker.MultipleLocator(1e9*60*xmajor))
    ax3a.xaxis.set_minor_locator(ticker.MultipleLocator(1e9*60*xminor))
    ax3a.xaxis.set_major_formatter(lambda x,p: pd.Timestamp(x).strftime('%H:%M'))
    ax3a.axvspan(pd.Timedelta('17:10:00').value, # HINT requires hh:mm:ss format
                  pd.Timedelta('17:16:00').value,
                  alpha=0.5, 
                  color='pink')
    ax3a.axvspan(pd.Timedelta('17:16:00').value,
                  pd.Timedelta('17:22:00').value,
                  alpha=0.8, 
                  color='skyblue')

for doy, grp in cycle3b:
    grp.index -= grp.index.floor('D')
    data = grp[colname] / max(grp[colname])
    
    ax3b.plot(data.index, data)
    ax3b.set_title('18:10-18:16 (after 13:00 PST Oct 26th)')
    ax3b.set_xlim(min(data.index).value, max(data.index).value)
    ax3b.yaxis.grid(which='major')
    ax3b.xaxis.grid(which='both')
    ax3b.xaxis.set_major_locator(ticker.MultipleLocator(1e9*60*xmajor))
    ax3b.xaxis.set_minor_locator(ticker.MultipleLocator(1e9*60*xminor))
    ax3b.xaxis.set_major_formatter(lambda x,p: pd.Timestamp(x).strftime('%H:%M'))
    ax3b.axvspan(pd.Timedelta('18:10:00').value, # HINT requires hh:mm:ss format
                  pd.Timedelta('18:16:00').value,
                  alpha=0.5, 
                  color='pink')
    ax3b.axvspan(pd.Timedelta('18:16:00').value,
                  pd.Timedelta('18:22:00').value,
                  alpha=0.8, 
                  color='skyblue')
    
for doy, grp in cycle4a:
    grp.index -= grp.index.floor('D')
    data = grp[colname] / max(grp[colname])
    
    ax4a.plot(data.index, data)
    ax4a.set_title('23:10-23:16 (before 13:00 PST Oct 26th)')
    ax4a.set_xlim(min(data.index).value, max(data.index).value)
    ax4a.yaxis.grid(which='major')
    ax4a.xaxis.grid(which='both')
    ax4a.xaxis.set_major_locator(ticker.MultipleLocator(1e9*60*xmajor))
    ax4a.xaxis.set_minor_locator(ticker.MultipleLocator(1e9*60*xminor))
    ax4a.xaxis.set_major_formatter(lambda x,p: pd.Timestamp(x).strftime('%H:%M'))
    ax4a.axvspan(pd.Timedelta('23:10:00').value, # HINT requires hh:mm:ss format
                  pd.Timedelta('23:16:00').value,
                  alpha=0.5, 
                  color='pink')
    ax4a.axvspan(pd.Timedelta('23:16:00').value,
                  pd.Timedelta('23:22:00').value,
                  alpha=0.8, 
                  color='skyblue')

for doy, grp in cycle4b:
    grp.index -= grp.index.floor('D')
    data = grp[colname] / max(grp[colname])
    
    ax4b.plot(data.index, data)
    ax4b.set_title('00:10-0:16 (after 13:00 PST Oct 26th)')
    ax4b.set_xlim(min(data.index).value, max(data.index).value)
    ax4b.yaxis.grid(which='major')
    ax4b.xaxis.grid(which='both')
    ax4b.xaxis.set_major_locator(ticker.MultipleLocator(1e9*60*xmajor))
    ax4b.xaxis.set_minor_locator(ticker.MultipleLocator(1e9*60*xminor))
    ax4b.xaxis.set_major_formatter(lambda x,p: pd.Timestamp(x).strftime('%H:%M'))
    ax4b.axvspan(pd.Timedelta('00:10:00').value, # HINT requires hh:mm:ss format
                  pd.Timedelta('00:16:00').value,
                  alpha=0.5, 
                  color='pink')
    ax4b.axvspan(pd.Timedelta('00:16:00').value,
                  pd.Timedelta('00:22:00').value,
                  alpha=0.8, 
                  color='skyblue')

很遗憾我受到环境的限制,仍然使用旧版本(例如 matplotlib 3.4.1,* panda 1.2.4*,numpy 1.20.2)。也许有一个问题已经解决,我应该更新?

In [25]: pd.show_versions()

INSTALLED VERSIONS
------------------
commit           : 2cb96529396d93b46abab7bbc73a208e708c642e
python           : 3.8.9.final.0
python-bits      : 64
OS               : Windows
OS-release       : 7
Version          : 6.1.7601
machine          : AMD64
processor        : Intel64 Family 6 Model 42 Stepping 7, GenuineIntel
byteorder        : little
LC_ALL           : None
LANG             : en
LOCALE           : English_United States.1252

pandas           : 1.2.4
numpy            : 1.20.2
pytz             : 2021.1
dateutil         : 2.8.1
pip              : 23.0
setuptools       : 56.0.0
Cython           : 0.29.23
pytest           : 6.2.3
hypothesis       : 6.9.2
sphinx           : 3.5.4
blosc            : 1.10.2
feather          : 0.4.1
xlsxwriter       : 1.3.9
lxml.etree       : 4.6.3
html5lib         : 1.1
pymysql          : None
psycopg2         : None
jinja2           : 2.11.3
IPython          : 7.22.0
pandas_datareader: 0.9.0
bs4              : 4.9.3
bottleneck       : 1.3.2
fsspec           : 0.8.7
fastparquet      : 0.5.0
gcsfs            : None
matplotlib       : 3.4.1
numexpr          : 2.7.3
odfpy            : None
openpyxl         : 3.0.7
pandas_gbq       : None
pyarrow          : 3.0.0
pyxlsb           : None
s3fs             : None
scipy            : 1.6.2
sqlalchemy       : 1.4.8
tables           : 3.6.1
tabulate         : None
xarray           : 0.17.0
xlrd             : None
xlwt             : None
numba            : 0.53.1
hwamh0ep

hwamh0ep1#

哎呀-没有明确的原因为什么它只影响子图(2,2),但一些重复调用轴格式化函数导致这种情况发生。
将格式化调用移出for..循环解决了该问题:

for doy, grp in cycle2b:
        grp.index -= grp.index.floor('D')
        data = grp[colname] / max(grp[colname])
        ax2b.plot(data.index, data)

    ax2b.set_title('12:10-12:16 (after 13:00 PST Oct 26th)')
    ax2b.set_xlim(min(data.index).value, max(data.index).value)
    ax2b.yaxis.grid(which='major')
    ax2b.xaxis.grid(which='both')
    ax2b.xaxis.set_major_locator(ticker.MultipleLocator(1e9*60*xmajor))
    ax2b.xaxis.set_minor_locator(ticker.MultipleLocator(1e9*60*xminor))
    ax2b.xaxis.set_major_formatter(lambda x,p: pd.Timestamp(x).strftime('%H:%M'))
    ax2b.axvspan(pd.Timedelta('12:10:00').value, # HINT requires hh:mm:ss format
                 pd.Timedelta('12:16:00').value,
                 alpha=0.5, 
                 color='pink')
    ax2b.axvspan(pd.Timedelta('12:16:00').value,
                 pd.Timedelta('12:22:00').value,
                 alpha=0.8, 
                 color='skyblue')

相关问题