Madhan
Madhan

Reputation: 1

Attachment of a dynamic matplotlib graph directly to html in flask

I'm measuring CPU & Memory usage of computer and plotting directly in a matplotlib graph, HOW COULD I PIN THIS GRAPH DIRECTLY TO HTML IN FLASK

'''def Live_data(): import matplotlib.pyplot as plt import psutil import time

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()'''

It would be better if I get the direct code for it, because giving documentation also OK.

Thanks for your contribution!!

Upvotes: 0

Views: 340

Answers (1)

Programmer Gaurav
Programmer Gaurav

Reputation: 449

Save your graph in the static folder
app.py

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

and in HTML use img tag to display the image
templates/index.html

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

Upvotes: 1

Related Questions