【问题标题】:Attachment of a dynamic matplotlib graph directly to html in flask将动态 matplotlib 图直接附加到烧瓶中的 html
【发布时间】:2020-10-25 01:42:42
【问题描述】:

我正在测量计算机的 CPU 和内存使用情况并直接在 matplotlib 图中进行绘图, 如何在 FLASK 中将此图直接固定到 HTML 中

'''def Live_data(): 将 matplotlib.pyplot 导入为 plt 导入psutil 进口时间

plt.figure(facecolor='w')


cpu_bar = plt.subplot(221)
cpu_line = plt.subplot(222)
memory_bar = plt.subplot(223)
memory_line = plt.subplot(224)

cpu_bar.set_position([0.125, 0.536, 0.1, 0.3])
cpu_line.set_position([0.3, 0.536, 0.6, 0.3])
memory_bar.set_position([0.125, 0.1, 0.1, 0.3])
memory_line.set_position([0.3, 0.1, 0.6, 0.3])

cpu_line.set_ylim(0, 100)
memory_line.set_ylim(0, 100)

cpu_line.set_xlim(0, 20)
memory_line.set_xlim(0, 20)

miloc_1 = plt.MultipleLocator(1)
miloc_2 = plt.MultipleLocator(10)
cpu_line.xaxis.set_minor_locator(miloc_1)
cpu_line.yaxis.set_minor_locator(miloc_2)
cpu_line.grid(which='minor', color='darkgray')
memory_line.xaxis.set_minor_locator(miloc_1)
memory_line.yaxis.set_minor_locator(miloc_2)
memory_line.grid(which='minor')

cpu_bar.get_xaxis().set_visible(False)
memory_bar.get_xaxis().set_visible(False)

x_2 = []
y_2 = []
x_4 = []
y_4 = []

width = 1
step = 0
while True:
    cpu_bar.cla()
    cpu_bar.set_ylim(0, 100)
    temp_cpu = psutil.cpu_percent()
    x_1 = [0]
    y_1 = [temp_cpu]
    cpu_bar.set_title(str(temp_cpu) + "%")
    cpu_bar.bar(x_1, y_1, width=width)

    x_2.append(step)
    y_2.append(temp_cpu)
    if step > 20:
        cpu_line.set_xlim(step - 20, step)
        memory_line.set_xlim(step - 20, step)
    cpu_line.plot(x_2, y_2, color='b')
    cpu_line.legend(['CPU usage(%)'], loc="upper right")
    cpu_line.set_xlabel('Time(s)')

    memory_bar.cla()
    memory_bar.set_ylim(0, 100)
    temp_memory = psutil.virtual_memory().percent
    x_3 = [0]
    y_3 = [temp_memory]
    memory_bar.set_title(str(temp_memory) + '%')
    memory_bar.bar(x_3, y_3, width=width, color='r')

    x_4.append(step)
    y_4.append(temp_memory)
    memory_line.plot(x_4, y_4, color='r', label='Memory')
    plt.xlabel('Time(s)')
    step += 1
    plt.legend(['Memory(%)'], loc="upper right")
    plt.pause(0.5)

plt.show()

Live_data()'''

如果我得到它的直接代码会更好,因为提供文档也可以。

感谢您的贡献!!

【问题讨论】:

  • “您的帖子看起来主要是代码;请添加更多详细信息。”

标签: python html matplotlib flask


【解决方案1】:

将图表保存在静态文件夹中
app.py

plt.savefig('static/graph.png')

在 HTML 中使用 img 标签来显示图像
templates/index.html

<img alt="Sample Work" src="{{ url_for('static', filename='graph.png') }}">

【讨论】:

  • 但是,我需要将它直接固定到烧瓶中的 html
猜你喜欢
  • 2013-12-05
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多