【问题标题】:Overlapping legend when create plot with matplotlib and mpld3 in python在 python 中使用 matplotlib 和 mpld3 创建绘图时重叠图例
【发布时间】:2017-09-05 14:03:47
【问题描述】:

我是 Python 编程领域的初学者,我很难弄清楚如何解决我的问题。

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

下面是我的剧情图片:

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

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)

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

【问题讨论】:

  • 我从未使用过mpld3,所以我不确定,但您可以尝试将InteractiveLegendPlugin 行移到for 循环之外。您可以将ptstr(i) 附加到一些列表中,然后一次性将它们提供给图例插件。
  • mpld3其实是用来将matplotlib嵌入到网页中的,谢谢你的建议,我会考虑一下的。
  • 实际上没有帮助

标签: python matplotlib plot legend mpld3


【解决方案1】:
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 时使用它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 2021-12-13
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多