关于Python:Python-matplotlib-PyQT:绘制到QPixmap

Python - matplotlib - PyQT: plot to QPixmap

我想可视化matplotlibs颜色图(类似于http://matplotlib.org/examples/color/colormaps_reference.html),并将其用作PyQt小部件中的QPixmaps。 想法是在matplotlib中创建图,而无需实际显示(或将其保存到文件中)并将其转换为QPixmap。 这里提供的解决方案(Python-matplotlib-PyQT:将图像复制到剪贴板)似乎不起作用,可能是因为我不想显示matplotlib图。


我尝试了以下方法,并且有效:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def testColourMap(cmap):
    sp = SubplotParams(left=0., bottom=0., right=1., top=1.)
    fig = Figure((2.5,.2), subplotpars = sp)
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    gradient = np.linspace(0, 1, 256)
    gradient = np.vstack((gradient, gradient))
    ax.imshow(gradient, aspect=10, cmap=cmap)
    ax.set_axis_off()
    canvas.draw()
    size = canvas.size()
    width, height = size.width(), size.height()
    im = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32)
    return QPixmap(im)