如何使用pyscript保存图形

how to save figure using pyscript

如标题所述,实际上我是 html 和 css 的菜鸟。那么我如何使用 savefig 或其他方法使用 matplotlib

保存绘图文件
<html>
  <body style="margin: 25px 75px 25px 75px;">
    <div class="p-5 text-center bg-light">
      <p>Quick Draw by<a href="https://github.com/ELongking"> <span>Longking</span> </a></p>
      <p><a href="https://github.com/pyscript/pyscript"><span>PyScript</span></a> is a very new framework, it needs a few seconds to load...</p>
      <h3>If you want to use it again, you need to refresh the page</h3>
    </div>
    
    <div class="container" id="test-plot">
    <p>Please enter your equation which is need to be drawn</p>
    <input id="eq" type="text" width="20" placeholder="y=2*x+sqrt(x)">
    <br>
    <p>Set the range of x coordinate</p>
    <input id="ra" type="text" width="20" placeholder="-5,5">
    <br>

    <p>Save or not</p>
    <input id="save" type="text" width="20" placeholder="yes or no">
    <br>

    <button id="but" style="margin-top: 10px;margin-bottom: 10px;" type="button" pys-onClick="main">
  Generate</button>
    </div>
    <py-script>

      from numpy import *
      from matplotlib import pyplot as plt, style as sty
      from js import console, document
      
      def main(*args,**kwargs):

        eq=document.getElementById("eq").value
        ra=document.getElementById("ra").value
        save=document.getElementById("save").value

        main_eq=eq.split('=')[1]
        if ra.find(',')>0:
          xmin,xmax=float(ra.split(',')[0]),float(ra.split(',')[1])
        else:
          xmin,xmax=-5,5

        x=linspace(xmin,xmax,1000)
        y=eval(main_eq)
        
        sty.use('seaborn-paper')
        fig, ax = plt.subplots()
        ax.plot(x, y,'--')

        if save=="yes":
          plt.savefig(r"D:\result.png",dpi=600)
        pyscript.write("test-plot",fig)

    </py-script>
    </div>
  </body>
</html>

我想把图存到result.png的D盘,但是没用。感谢您的解决方案。

以下代码行写入浏览器的虚拟文件系统而不是用户的桌面文件系统:

plt.savefig(r"D:\result.png",dpi=600)

解决方法是使用浏览器文件系统API写入用户桌面文件系统

首先,将数据保存为BytesIO并调用一个函数来执行文件保存:

buf = io.BytesIO()
plt.savefig(buf, format='png')
await save_file(buf)

文件保存功能将与浏览器的文件系统接口:

import asyncio
from js import console, document, window, Blob
from pyodide import to_js

async def save_file(buf):
        try:
                # Read and convert to a JavaScript array
                buf.seek(0)
                content = to_js(buf.read())

                # Create a JavaScript Blob and set the Blob type as a PNG
                b = Blob.new([content], {type: "image/png"})

                # Perform the actual file system save 
                fileHandle = await window.showSaveFilePicker()
                file = await fileHandle.createWritable()
                await file.write(b)
                await file.close()
        except Exception as e:
                console.log('Exception: ' + str(e))
                return

我写了一篇文章来帮助解释与浏览器文件系统的接口:

Pyscript: Files and File Systems – Part 2