I am new to matplotlib, I got exception
Traceback (most recent call last):
File "C:\Users\Oscar\Documents\ConsumerSoftwareProject\Plot\plot.py", line 164, in <module>
app = ApplicationWindow()
File "C:\Users\Oscar\Documents\ConsumerSoftwareProject\Plot\plot.py", line 54, in __init__
self.h3pr(path=r'2020.12\20201231\I20201231080000.Pr01.nc', ax=self.ax)
File "C:\Users\Oscar\Documents\ConsumerSoftwareProject\Plot\plot.py", line 135, in h3pr
cb = m.colorbar()
File "C:\Users\Oscar\AppData\Local\Programs\Python\Python39\lib\site-packages\mpl_toolkits\basemap\__init__.py", line 4647, in colorbar
fig.sca(ax) # reset parent axes as current axes.
File "C:\Users\Oscar\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\figure.py", line 1535, in sca
self._axstack.bubble(a)
File "C:\Users\Oscar\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\figure.py", line 82, in bubble
return super().bubble(self._entry_from_axes(a))
File "C:\Users\Oscar\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\cbook\__init__.py", line 638, in bubble
raise ValueError('Given element not contained in the stack')
ValueError: Given element not contained in the stack
with the following code, how to fix it ?
import sys
import time
import numpy as np
from matplotlib.backends.qt_compat import QtWidgets
from matplotlib.backends.backend_qtagg import (
FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
from matplotlib.figure import Figure
import netCDF4 as nc
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
# import pandas as pd
import matplotlib.ticker as mticker
import numpy as np
from matplotlib.patches import Rectangle
import matplotlib as mpl
from mpl_toolkits.basemap import Basemap
from matplotlib.font_manager import FontProperties # 使能够显示中文
from matplotlib.patches import Polygon
import matplotlib.patches as mpatches
from datetime import datetime
from netCDF4 import Dataset
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
class ApplicationWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self._main = QtWidgets.QWidget()
self.setCentralWidget(self._main)
layout = QtWidgets.QVBoxLayout(self._main)
self.map_canvas = FigureCanvas(Figure(figsize=(5, 3)))
# Ideally one would use self.addToolBar here, but it is slightly
# incompatible between PyQt6 and other bindings, so we just add the
# toolbar as a plain widget instead.
layout.addWidget(NavigationToolbar(self.map_canvas, self))
layout.addWidget(self.map_canvas)
self.ax = self.map_canvas.figure.subplots()
self.ax.set_axis_off()
# t = np.linspace(0, 10, 501)
# self.ax.plot(t, np.tan(t), ".")
# print(self.ax.plot([1, 2, 3], [1, 4, 9]))
# help(self.ax)
self.h3pr(path=r'2020.12\20201231\I20201231080000.Pr01.nc', ax=self.ax)
def h3pr(self, path=r'2020.12\20201231\I20201231080000.Pr01.nc', ax=''):
self.ax.clear()
# path
# path = f"{startingDateTime:%Y.%m\\%Y%m%d\\I%Y%m%d%H}0000.{'Pr01' if interval<12 else 'Pr12'}.nc"
# sc = MplCanvas(None, width=5, height=4, dpi=100)
# sc.axes.plot([0, 1, 2, 3, 4], [10, 1, 20, 3, 40])
nc_obj = Dataset(path)
# print(nc_obj)
a = 3
fname = path.split("\\")[-1]
yy = fname[1:5]
mm = fname[5:7]
dd = fname[7:9]
hh = fname[9:11]
hh2 = int(hh) + a
if hh2 >= 24:
hh2 = hh2 - 24
hh22 = str(hh2)
else:
hh22 = str(hh2)
lat = (nc_obj.variables['lat'][:])
lon = (nc_obj.variables['lon'][:])
Pr01 = (nc_obj.variables['Pr01'][:])
#print(Pr01[0, :, :])
pr = Pr01[0, :, :]
for t in range(1, a):
pr[:, :] = Pr01[t, :, :] + pr[:, :]
m = Basemap(projection='cyl', llcrnrlon=np.min(lon), llcrnrlat=np.min(lat), urcrnrlon=np.max(lon),
urcrnrlat=np.max(lat), resolution='h', ax=ax,)
Lon, Lat = np.meshgrid(lon[:], lat[:])
X, Y = m(Lon, Lat)
# m.drawcoastlines(linewidth=0.5)
m.drawcountries(linewidth=0.5)
m.readshapefile(r'CHN_adm_shp\CHN_adm1', 'states', linewidth=0.3, drawbounds=True, color='k')
title = yy + '.' + mm + '.' + dd + ' ' + hh + ':00-' + mm + '.' + dd + ' ' + hh22 + ':00'
# plt.title(title, fontproperties='Times New Roman', fontsize='10')
levels = np.linspace(0, 50, 11)
from matplotlib import cm
cs = m.contourf(X, Y, pr, levels=levels, cmap=cm.jet, extend='both')
cb = m.colorbar(cs, location="right", size="5%", pad='2%', ticks=[0, 2.5, 5, 7.5, 10, 12.5, 15, 17.5, 20, 22.5], ax=ax,)
cb = m.colorbar(cs, location="right", size="5%", ticks=np.linspace(0, 50, 11), pad='2%', ax=ax,)
# cb = m.colorbar(cs, location='right', pad="5%")
cb.set_label('precipitation(mm)')
x_major_locator = MultipleLocator(0.5) # x坐标间隔
y_major_locator = MultipleLocator(0.5) # y坐标间隔
ax.set_yticks(lat)
ax.set_xticks(lon)
ax.set_ylabel('Latitude(°N)', fontproperties='Times New Roman', fontsize='14')
ax.set_xlabel('Longitude(°E)', fontproperties='Times New Roman', fontsize='14')
# ax.set_xticklabels("%.1f" % i for i in [121, 121.5, 122, 122.5, 123, 123.5]) # x轴刻度标签
# ax.set_yticklabels("%.1f" % i for i in [29, 29.5, 30, 30.5, 31, 31.5]) # y轴刻度标签
ax.xaxis.set_major_locator(x_major_locator)
ax.yaxis.set_major_locator(y_major_locator)
if __name__ == "__main__":
# Check whether there is already a running QApplication (e.g., if running
# from an IDE).
qapp = QtWidgets.QApplication.instance()
if not qapp:
qapp = QtWidgets.QApplication(sys.argv)
app = ApplicationWindow()
app.show()
app.activateWindow()
app.raise_()
qapp.exec()