2

I am plotting two graphs. I am trying to plot multiple matplotlib graphs on my web browser using the mpld3 library. I am successful in plotting the first graph with the help of mpld3.show() function, but the other graph is not being loaded.

Can anyone help me out on how to get both the graphs on the browser, I am sure it a single line of code that will solve the issue.

import matplotlib.pyplot as plt, mpld3

x = [1,2,3]
y = [2,3,4]

#firstgraph
plt.xlabel("xlabel 1")
plt.ylabel("ylabel 1")
plt.title("Plot 1")
plt.legend()
plt.bar(x,y, label = 'label for bar', color = 'b')
mpld3.show()

#secondgraph
x = [1,2,3]
y = [5,3,1]
plt.xlabel("xlabel 2")
plt.ylabel("ylabel 2")
plt.title("Plot 2")
plt.bar(x,y, color = 'r')
mpld3.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
prime
  • 47
  • 1
  • 7
  • No, the graphs are being generated just fine using the plt.show() function, I am using the mpld3 library to display it on my web browser, when I execute the code, only the first graph is being displayed on the browser not the second, what I want is both graphs being displayed side by side or one below the other. I think right now one both graphs are being generated one behind the other. – prime Nov 18 '17 at 19:43
  • You are welcome to execute the code, it will take just a second to understand what I mean, if you use the plt.show() both graphs are being generated , from my IDE, but when using the mpld3 to display it on my browser only the first graph that is miles walked per week is being dispalyed – prime Nov 18 '17 at 19:44

1 Answers1

4

As with plt.show() the execution of the script will stop while the output is served to the browser.

You may press Ctrl+C to stop the server, such that the code continues with the second figure. The second figure will then be shown in a new browser tab.

On the other hand you may also serve both figures simultaneously to the browser by creating their html representation individually and joining the html to be served.

import matplotlib.pyplot as plt
import mpld3
from mpld3._server import serve

#firstgraph
x = [1,2,3]
y = [2,3,4]
fig1 = plt.figure()
plt.xlabel("xlabel 1")
plt.ylabel("ylabel 1")
plt.title("Plot 1")
plt.legend()
plt.bar(x,y, label = 'label for bar', color = 'b')

#secondgraph 
x = [1,2,3]
y = [5,3,1]
fig2 =plt.figure()
plt.xlabel("xlabel 2")
plt.ylabel("ylabel 2")
plt.title("Plot 2")
plt.bar(x,y, color = 'r')

# create html for both graphs 
html1 = mpld3.fig_to_html(fig1)
html2 = mpld3.fig_to_html(fig2)
# serve joined html to browser
serve(html1+html2)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712