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

1 回答 1

4

plt.show()输出提供给浏览器时,脚本的执行将停止。

您可以按Ctrl+C停止服务器,以便代码继续第二个数字。然后第二个图形将显示在新的浏览器选项卡中。

另一方面,您也可以通过分别创建它们的 html 表示并加入要提供的 html 来同时向浏览器提供这两个图形。

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)
于 2017-11-18T20:22:06.747 回答