Deepin - Pycharm调试记录 - Matplot3D动态画图报错问题
写在开头的话
应该不会有人傻到看这个wiki吧,我花了1个小时才发现问题,是我自己方法调错了。
这个wiki不会细致的教大家如何使用matplotlib进行动态画图,或者动态画图的几种办法,记录一下花了一个小时左右调试出动态画图bug,希望如果有人遇到这个问题可以借鉴一下。和上一篇文章Pyinstaller索引系统库问题一样,最终的思路还是阅读源码。前面看github各种开源代码和matplotlib的文档浪费了太多时间不如直接阅读源码效率高。
现象
我有一个画图函数,放置在3D画布上进行构图,初始化函数如下:这是一个3D构图,
其中,
self.xedges 是x坐标
self.yedges是y坐标
self.hist是z坐标
self.color_list是颜色图
class MyFigure(FigureCanvas):def __init__(self, width=5, height=4, dpi=100):self.fig = Figure(figsize=(width, height), dpi=dpi)super(MyFigure, self).__init__(self.fig)self.axes = self.fig.add_subplot(111, projection='3d')# 设置x轴取值self.xedges = np.array([[10, 20], [10, 20], [10, 20], [10, 20],[20, 30], [20, 30], [20, 30], [20, 30],[30, 40], [30, 40], [30, 40], [30, 40],[40, 50], [40, 50], [40, 50], [40, 50]])# 设置y轴取值self.yedges = np.array([[10, 20], [20, 30], [30, 40], [40, 50],[10, 20], [20, 30], [30, 40], [40, 50],[10, 20], [20, 30], [30, 40], [40, 50],[10, 20], [20, 30], [30, 40], [40, 50],[10, 20], [20, 30], [30, 40], [40, 50]])# 设置X,Y对应点的值。即原始数据。self.hist = np.array([[3.0], [0.0], [8.0], [4.0],[2.0], [4.0], [5.0], [7.0],[9.0], [2.0], [6.0], [3.0],[0.0], [3.0], [1.0], [0.0]])self.color_list = ['skyblue', 'lightgreen', 'bisque', 'gold','lightgreen', 'bisque', 'gold', 'lightpink','bisque', 'gold', 'lightpink', 'plum','gold', 'lightpink', 'plum', 'lightgray']
实际绘图函数在这里,是一个for循环,原来画2D图时候,直接调用draw()方法就可以完成动态图绘制。但是现在调用时候,报错。
def plot_city_line(self):for i in range(len(self.xedges)):# 设置作图点的坐标xpos, ypos = np.meshgrid(self.xedges[i][:-1] - 2.5, self.yedges[i][:-1] - 2.5)xpos = xpos.flatten('F')ypos = ypos.flatten('F')zpos = np.zeros_like(xpos)# 设置柱形图大小dx = 5 * np.ones_like(zpos)dy = dx.copy()dz = self.hist[i].flatten()# 设置坐标轴标签self.axes.set_xlabel('side')self.axes.set_ylabel('front')self.axes.set_zlabel('height')self.axes.bar3d(xpos, ypos, zpos, dx, dy, dz, color=self.color_list[i], zsort='average')self.axes.draw()
解决办法
重新调试的时候发现,draw() 方法是针对figure来说的,而不是针对于坐标轴来说的,因此,使用
self.draw()
或者
self.figure.canvas.draw()
都可以完成画图
源码
^ _ ^,是我自己代码一开始写错了纠结了半天,好坑阿!
参考代码路径
./venv/Lib/site-packages/mpl_toolkits/tests/test_mplot3d.py
第666行左右的函数
def test_patch_modification():fig = plt.figure()ax = fig.add_subplot(projection="3d")circle = Circle((0, 0))ax.add_patch(circle)art3d.patch_2d_to_3d(circle)circle.set_facecolor((1.0, 0.0, 0.0, 1))assert mcolors.same_color(circle.get_facecolor(), (1, 0, 0, 1))fig.canvas.draw()assert mcolors.same_color(circle.get_facecolor(), (1, 0, 0, 1))