LucasRussi
LucasRussi

Reputation: 23

TypeError: QPixmap(): argument 1 has unexpected type 'Figure'

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))

Upvotes: 2

Views: 1537

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

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:

Upvotes: 2

Related Questions