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

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

我正在尝试使用 matplotlib 制作图表并使用 Qpixmap 将其直接绘制在 Qlabel 中。但是,错误 QPixmap () 正在发生:argument 1 has unexpected type 'Figure'。如何在不保存图表的情况下显示图表?

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

您无法转换 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_())

注意:不需要转换为QPixmap来显示matplotlib图,因为matplotlib允许使用Qt作为后端,我建议检查以下内容post :