在python中使用matplotlib和mpld3创建绘图时重叠的图例

时间:2017-09-05 14:03:48

标签: python matplotlib plot legend mpld3

我是python编程世界的初学者,我很难弄清楚如何解决我的问题。

问题是当我使用matplotlib和mpld3在python中创建一个使用循环的情节时,情节就像我预期的那样,但情节的传说确实是错误的,因为传说彼此重叠。仅显示最新数据的图表图例,因为其他数据的图例重叠在其上。

下面是我的情节图片:

Image

这是在循环中创建绘图和图例的代码:

plt.rcParams.update({'font.size': 13})
fig, ax = plt.subplots()
for i in range(3,5):
        rd1 = pd.read_sql_query("SELECT press, rs FROM basic_chart WHERE 
        cs = "+str(i), app.config['SQLALCHEMY_DATABASE_URI'])
        print(rd1)
        pt = ax.plot(rd1['press'],rd1['rs'],'-o')
        plugins.connect(fig, plugins.InteractiveLegendPlugin([pt],[str(i)]))
html = mpld3.fig_to_html(fig)

我认为主要问题在于交互式图例代码,但我没有设法找出纠正它的正确方法。我真的希望专家可以帮助我解决这个问题。

1 个答案:

答案 0 :(得分:0)

plt.rcParams.update({'font.size': 13})
fig, ax = plt.subplots()
for i in range(3,5):
    rd1 = pd.read_sql_query("SELECT press, rs FROM basic_chart WHERE 
    cs = "+str(i), app.config['SQLALCHEMY_DATABASE_URI'])
    print(rd1)
    pt = ax.plot(rd1['press'],rd1['rs'],'-o')

axhandles, axlabels = ax.get_legend_handles_labels()
plugins.connect(fig, plugins.InteractiveLegendPlugin(axhandles, axlabels))
html = mpld3.fig_to_html(fig)

通过在循环中使用plugins.connect,您将创建两个单独的图例。 绘图后,从绘图中获取句柄和标签,并在调用InteractiveLegendPlugin时使用它。