Issue
I'm trying to make a graph using matplotlib and plot it directly in a Qlabel using Qpixmap. However, the error QPixmap () is happening: argument 1 has unexpected type 'Figure'. How do I display the graph without saving it before?
import matplotlib.pyplot as plt
import numpy as np
labels = ['Word', 'Excel', 'Chrome','Visual Studio Code']
title = [20,32,22,25]
cores = ['lightblue','green','blue','red']
explode = (0,0.1,0,0)
plt.rcParams['font.size'] = '16'
total=sum(title)
plt.pie(title,explode=explode,labels=labels,colors=cores,autopct=lambda p: '{:.0f}'.format(p*total/100), shadow=True, startangle=90)
plt.axis('equal')
grafic = plt.gcf()
self.ui.grafig_1.setPixmap(QPixmap(grafic))
Solution
You cannot convert a Figure
to QPixmap
directly, so you get that exception. Instead you must get the bytes of the image generated by the savefig()
method of Figure
and with it create a QPixmap
:
import io
import sys
import matplotlib.pyplot as plt
import numpy as np
from PyQt5 import QtGui, QtWidgets
labels = ["Word", "Excel", "Chrome", "Visual Studio Code"]
title = [20, 32, 22, 25]
cores = ["lightblue", "green", "blue", "red"]
explode = (0, 0.1, 0, 0)
plt.rcParams["font.size"] = "16"
total = sum(title)
plt.pie(
title,
explode=explode,
labels=labels,
colors=cores,
autopct=lambda p: "{:.0f}".format(p * total / 100),
shadow=True,
startangle=90,
)
plt.axis("equal")
grafic = plt.gcf()
f = io.BytesIO()
grafic.savefig(f)
app = QtWidgets.QApplication(sys.argv)
label = QtWidgets.QLabel()
pixmap = QtGui.QPixmap()
pixmap.loadFromData(f.getvalue())
label.setPixmap(pixmap)
label.show()
sys.exit(app.exec_())
Note: It is not necessary to convert to QPixmap to display a matplotlib plot since matplotlib allows to use Qt as a backend, I recommend checking the following post:
- How to embed matplotlib in pyqt - for Dummies
- https://matplotlib.org/3.3.3/gallery/user_interfaces/embedding_in_qt_sgskip.html
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.