简体   繁体   English

在 PyQt 中嵌入 matplotlib 颜色条

[英]Embed matplotlib colorbar in PyQt

I am developping an app with PyQt4 where I need to display graphs with Matplotlib.我正在使用 PyQt4 开发一个应用程序,我需要在其中使用 Matplotlib 显示图形。 To do so, I use the following code, which works well :为此,我使用以下代码,效果很好:

self.PhaFig = fig.Figure() #Creation of the Figure
self.PhaBeamCanvas = FigureCanvasQTAgg(self.PhaFig) #Creation of the display canvas
self.AxesPhaInit = self.PhaFig.add_subplot(111, title = "Input beam phase", aspect = 'equal') #Creation of the axes object inside the Figure
imgPha = self.AxesPhaInit.imshow(self.wf_mask,extent =[-xx/2+xx/N,xx/2,-xx/2+xx/N,xx/2])
self.PhaFig.colorbar(imgPha) #adding a colorbar to the graph
self.PhaBeamCanvas.draw() #drawing on the canvas

This graph is updated when a button is pushed.当按下按钮时,此图会更新。 The update of the graph works well.图形的更新效果很好。 The problem comes from the colorbar.问题来自颜色条。 When a new graph is drawn, the previous colorbar is not deleted and the new one is drawn near to the old one.绘制新图形时,不会删除先前的颜色条,而是将新的颜色条靠近旧的颜色条。

I have tried something like :我试过类似的东西:

self.PhaFig.delaxes(self.AxesPhaInit)

But this does not work.但这不起作用。 The graph is deleted but not the colorbar, and the next graph display does not work anymore.图形被删除,但颜色条不删除,下一个图形显示不再起作用。

Does someone have an idea?有人有想法吗?

colorbar ( docs ) has a kwarg cax which in the axis into which the colorbar should be drawn. colorbar ( docs ) 有一个 kwarg cax ,它位于应该绘制颜色cax的轴上。 The default behaver is to 'steal' space in the figure from (iirc) the axes in which the colormappable is living.默认行为是从 (iirc) 颜色映射所在的轴“窃取”图中的空间。

Once you have handles on the Axes objects there is no difference between embedding or not embedding so I will demonstrate with non-embedded (which is really just pre-embedded, but I digress).一旦您处理了Axes对象,嵌入或不嵌入就没有区别了,所以我将用非嵌入(这实际上只是预嵌入,但我离题了)进行演示。

fig, (ax, cax) = plt.subplots(1, 2)
img = ax.imshow(np.random.rand(42, 42))
fig.colorbar(img, cax=cax)

You will obviously need to size your cax more sensibly and some of the other kwargs on colorbar can help with that.显然,您cax更明智地cax大小,而cax条上的其他一些kwargs可以帮助解决此问题。

I guess I'm a little late to this party, but I found a super simple way to solve this problem (which I was encountering myself in my own app).我想我参加这个聚会有点晚了,但我找到了一个超级简单的方法来解决这个问题(我在自己的应用程序中遇到了这个问题)。

Each time you update or redraw the plot in the pyqt app, call:每次在 pyqt 应用程序中更新或重绘绘图时,调用:

self.PhaFig.clf()

Then add your suplots and draw etc.然后添加你的 suplots 和 draw 等。

Unbelievably enough...It's as simple as that!难以置信……就这么简单! just using clf refreshes the figure by getting rid of what it contained before.仅使用 clf 即可通过摆脱之前包含的内容来刷新数字。

At least, this worked for me in PyQt5.至少,这在 PyQt5 中对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM