【问题标题】:TypeError: QPixmap(): argument 1 has unexpected type 'Figure'TypeError:QPixmap():参数 1 具有意外类型“Figure”
【发布时间】:2021-03-18 05:01:18
【问题描述】:

我正在尝试使用 matplotlib 制作图表,并使用 Qpixmap 将其直接绘制在 Qlabel 中。但是,错误 QPixmap () 正在发生:参数 1 具有意外类型“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))

【问题讨论】:

    标签: python python-3.x matplotlib pyqt pyqt5


    【解决方案1】:

    您无法将 Figure 直接转换为 QPixmap,因此您会遇到该异常。相反,您必须获取由Figuresavefig() 方法生成的图像字节,并用它创建一个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_())
    

    注意:由于 matplotlib 允许使用 Qt 作为后端,因此无需转换为 QPixmap 即可显示 matplotlib 图,我建议查看以下帖子:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-27
      • 2012-12-12
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2015-04-12
      相关资源
      最近更新 更多