【问题标题】:Matplotlib - export figure to png in memory bufferMatplotlib - 将图形导出到内存缓冲区中的 png
【发布时间】:2020-05-07 15:50:44
【问题描述】:

是否可以将 matplotlib 图形作为 png 导出为字节类型? 这是我目前拥有的代码:

def import_chart(df, x_label, y_label, title):
    fig, ax = plt.subplots()
    ax.plot(data[x_label], data[y_label])

    ax.set(xlabel=x_label, ylabel=y_label,
           title=title)
    image_name = 'test.png'

    fig.savefig(image_name)
    f = open(image_name, 'rb+')
    img = f.read()
    f.close()
    os.remove(image_name)

    return img

返回的图像属于“字节”类。我想避免保存到硬盘驱动器并再次读取它。像这样的:

def import_chart(self, x_label, y_label, title):
    fig, ax = plt.subplots()
    data = self.file_data.get_column([x_label,y_label])
    ax.plot(data[x_label], data[y_label])

    ax.set(xlabel=x_label, ylabel=y_label,
           title=title)
    buffer = buffer.to_buffer(fig.savefig(), format='png')
    img = buffer.read()
    return img

【问题讨论】:

    标签: python matplotlib buffer


    【解决方案1】:

    我一直在使用它从网络服务器渲染 matplotlib 图像:

    import base64
    from io import BytesIO
    
    ...
    
    buffer = BytesIO()
    plt.savefig(buffer, format='png')
    buffer.seek(0)
    image_png = buffer.getvalue()
    buffer.close()
    graphic = base64.b64encode(image_png)
    graphic = graphic.decode('utf-8')
    
    return graphic
    

    【讨论】:

      猜你喜欢
      • 2019-04-13
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-02
      • 2012-03-28
      • 1970-01-01
      相关资源
      最近更新 更多