【问题标题】:Adding tooltip to multi line plot using mpld3使用 mpld3 向多线图添加工具提示
【发布时间】:2016-06-19 17:57:32
【问题描述】:

我完全是网络开发的菜鸟。我正在开发一个flask 应用程序,它使用matplotlib 从pandas 数据框中绘制多线图,但我希望通过mpld3 向数据点添加工具提示。 mpld3tooltip example 仅适用于散点图。如何为多线图执行此操作?

data = {'year': [2010, 2011, 2012, 2013, 2014, 2015, 2016,2017, 2018, 2019],
        'shop1': [10, 21, 20, 10, 23, 30, 31,45, 23, 56],
        'shop2': [10, 21, 20, 10, 12, 30, 78,45, 23, 56],
        'shop3': [10, 21, 20, 10, 34, 98, 31,45, 23, 56],}

df = pd.DataFrame(data)
df = df.set_index('year')
fig, ax = plt.subplots()
df.plot(ax=ax, marker='o')  
plt.grid(True)

mpld3.display()

【问题讨论】:

    标签: python matplotlib plot mpld3


    【解决方案1】:

    mpld3 似乎没有提供线图工具提示,因此您必须使用点工具提示并将其调整为线图。这里的重要观察是点工具提示依赖于 matplotlib 标记(参见讨论 here)。显然,对于许多线图,您可能不需要标记,所以我下面的示例关闭了标记颜色。 (我的例子是官方文档中点工具提示的example的修改版)

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    import mpld3
    from mpld3 import plugins
    import quandl
    
    
    # Define some CSS to control our custom labels
    css = """
    table
    {
      border-collapse: collapse;
    }
    th
    {
      color: #ffffff;
      background-color: #000000;
    }
    td
    {
      background-color: #cccccc;
    }
    table, th, td
    {
      font-family:Arial, Helvetica, sans-serif;
      border: 1px solid black;
      text-align: right;
    }
    """
    
    fig, ax = plt.subplots()
    
    df = quandl.get("YALE/SPCOMP")
    ts = df['S&P Composite']
    
    labels = []
    for dt in ts.index:
        labels.append( str(dt) + '<br/>' + str(ts.loc[dt]))
    
    lines = plt.plot(ts.index, ts.values, marker='o', ls='-', ms=5, markerfacecolor='None',markeredgecolor='None',)
    
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_title('HTML tooltips', size=20)
    
    tooltip = plugins.PointHTMLTooltip(lines[0], labels,
                                       voffset=10, hoffset=10, css=css)
    plugins.connect(fig, tooltip)
    
    mpld3.display()
    

    【讨论】:

      猜你喜欢
      • 2017-04-17
      • 1970-01-01
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 2017-02-28
      • 1970-01-01
      • 2011-10-30
      相关资源
      最近更新 更多