Setting a fixed size for points in legend

前端 未结 5 1343
温柔的废话
温柔的废话 2020-12-08 10:06

I\'m making some scatter plots and I want to set the size of the points in the legend to a fixed, equal value.

Right now I have this:

import matplotl         


        
5条回答
  •  感动是毒
    2020-12-08 10:27

    Just another alternative here. This has the advantage that it would not use any "private" methods and works even with other objects than scatters present in the legend. The key is to map the scatter PathCollection to a HandlerPathCollection with an updating function being set to it.

    def update(handle, orig):
        handle.update_from(orig)
        handle.set_sizes([64])
    
    plt.legend(handler_map={PathCollection : HandlerPathCollection(update_func=update)})
    

    Complete code example:

    import matplotlib.pyplot as plt
    import numpy as np; np.random.seed(42)
    from matplotlib.collections import PathCollection
    from matplotlib.legend_handler import HandlerPathCollection, HandlerLine2D
    
    colors = ["limegreen", "crimson", "indigo"]
    markers = ["o", "s", r"$\clubsuit$"]
    labels = ["ABC", "DEF", "XYZ"]
    plt.plot(np.linspace(0,1,8), np.random.rand(8), marker="o", markersize=22, label="A line")
    for i,(c,m,l) in enumerate(zip(colors,markers,labels)):
        plt.scatter(np.random.rand(8),np.random.rand(8), 
                    c=c, marker=m, s=10+np.exp(i*2.9), label=l)
    
    def updatescatter(handle, orig):
        handle.update_from(orig)
        handle.set_sizes([64])
    
    def updateline(handle, orig):
        handle.update_from(orig)
        handle.set_markersize(8)
    
    plt.legend(handler_map={PathCollection : HandlerPathCollection(update_func=updatescatter),
                            plt.Line2D : HandlerLine2D(update_func = updateline)})
    
    plt.show()
    

提交回复
热议问题