JavaScript调用Python脚本后Matplotlib绘图窗口无法自动关闭
Matplotlib绘图窗口调用plt.close('all')无法自动关闭
我编写了JavaScript脚本open_hist_w_user.js,通过spawn启动Python进程并将数据传递给create_histogram.py脚本。该Python脚本使用Matplotlib库生成并显示直方图,但调用plt.close('all')后绘图窗口仍无法关闭。我期望直方图生成后延迟一段时间自动关闭窗口,此前尝试用Plotly和df3将代码迁移到JavaScript但未成功,因此采用控制台传递数据的方式。
代码
JavaScript脚本:open_hist_w_user.js
/** * This script is used to spawn a python process that generates a histogram for the specified username. * * @param {string} username - The username for which the histogram is being generated. * * @returns {ChildProcess} - The spawned python process. */ const { spawn } = require('child_process'); const username = 'some_username'; const pythonProcess = spawn('python', ['./create_histogram.py', username]);
Python脚本:create_histogram.py
import matplotlib.pyplot as plt import sys import time def create_histogram(username): """ This function creates a histogram of data, with a specified number of bins and range, and displays it. Parameters ---------- username : str The username for which the histogram is being generated. Returns ------- None """ plt.close('all') # close any previous plot windows # plot the histogram plt.clf() # clear the previous plot plt.hist([1, 2, 3, 4, 5], bins=3, range=(0, 5)) plt.xlabel('Total') plt.ylabel('Frequency') plt.title(f'Histogram of Total Column for {username}') plt.show() # show the plot time.sleep(5) # wait for 5 seconds plt.close('all') # close the plot window if __name__ == "__main__": username = sys.argv[1] create_histogram(username)
预期结果
直方图显示5秒后自动关闭绘图窗口
实际结果

内容的提问来源于stack exchange,提问作者Iftikhar Ramnandan
相关产品推荐
相关产品推荐

