【问题标题】:How do I achieve hover xy data for matplotlib如何为 matplotlib 实现悬停 xy 数据
【发布时间】:2021-08-02 16:20:42
【问题描述】:

我正在尝试绘制图表:

ax = df.plot(x=1, y=2, marker = 'D', markersize=4)

X 轴来自第 1 列,y 轴来自第 2 列。
鼠标悬停时是否可以获得(x,y)?

【问题讨论】:

    标签: python pandas csv matplotlib


    【解决方案1】:

    mplcursors 是一些 matplotlib 开发人员提供的一个库,用于帮助在悬停时显示注释。这是一个例子:

    import matplotlib.pyplot as plt
    import mplcursors
    import pandas as pd
    import numpy as np
    
    def show_info(sel):
        ind = sel.target.index
        sel.annotation.set_text(f'{df.loc[ind, "Name"]}:\nHeight:{df.loc[ind, "Height"]}\nWeight:{df.loc[ind, "Weight"]}')
    
    heights = [174, 147, 155, 172, 187, 144, 181, 172, 143, 178, 181, 198, 142, 154, 159, 144, 194, 171, 140, 140, 192, 174,
               177, 158, 141, 184, 145, 183, 188, 181, 191, 153, 159, 141, 168, 190, 166, 149, 151, 188, 171, 142, 187, 179,
               184, 174, 151, 178, 177, 169, 169, 165, 140, 165, 182, 146, 176, 179, 198, 183, 187, 173]
    weights = [96, 92, 51, 139, 62, 80, 111, 105, 88, 117, 51, 50, 69, 105, 154, 108, 115, 147, 79, 52, 101, 138, 117, 95,
               94, 57, 99, 138, 123, 141, 62, 70, 104, 86, 50, 80, 107, 100, 82, 114, 141, 135, 140, 83, 83, 90, 62, 142,
               117, 136, 110, 143, 146, 62, 73, 70, 77, 56, 109, 131, 80, 131]
    
    df = pd.DataFrame({'Name': ["".join(np.random.choice(list('TUVWXYZ'), 5)) for _ in heights],
                       'Height': heights,
                       'Weight': weights})
    
    ax = df.plot(x=1, y=2, marker='D', markersize=4, ls='')
    mplcursors.cursor(hover=True).connect('add', show_info)
    
    plt.show()
    

    【讨论】:

    • 如果这回答了你的问题,你可以考虑投票和/或accepting答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多