【问题标题】:Matplotlib Hover TextMatplotlib 悬停文本
【发布时间】:2020-04-02 08:56:20
【问题描述】:

我使用 Matplotlib 和 Squarify 创建了这个 tree map。当鼠标悬停在轴上时,有没有办法显示有关每个轴的信息?

【问题讨论】:

    标签: python matplotlib data-visualization mplcursors squarify


    【解决方案1】:

    mplcursors 库可用于在悬停时创建自定义注释。这是一个带有树形图的示例:

    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import squarify
    import mplcursors
    
    sizes = [5, 20, 30, 25, 10, 12]
    sumsizes = sum(sizes)
    labels = ['A', 'B', 'C', 'D', 'E', 'F']
    
    cmap = plt.cm.get_cmap('Greens')
    norm = plt.Normalize(vmin=min(sizes), vmax=max(sizes))
    colors = [cmap(norm(s)) for s in sizes]
    squarify.plot(sizes=sizes, label=labels, color=colors)
    plt.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=norm))
    
    cursor = mplcursors.cursor(hover=True)
    cursor.connect("add", lambda sel: sel.annotation.set_text(
        f"ID:{sel.target.index} '{labels[sel.target.index]}'\nSize:{sizes[sel.target.index]} ({sizes[sel.target.index] * 100.0 / sumsizes:.1f} %)"))
    
    plt.show()
    

    【讨论】:

    • 是的!谢谢!
    猜你喜欢
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 2011-08-21
    • 2017-10-25
    相关资源
    最近更新 更多