Setting a fixed size for points in legend

前端 未结 5 1344
温柔的废话
温柔的废话 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条回答
  •  猫巷女王i
    2020-12-08 10:24

    You can make a Line2D object that resembles your chosen markers, except with a different marker size of your choosing, and use that to construct the legend. This is nice because it doesn't require placing an object in your axes (potentially triggering a resize event), and it doesn't require use of any hidden attributes. The only real downside is that you have to construct the legend explicitly from lists of objects and labels, but this is a well-documented matplotlib feature so it feels pretty safe to use.

    from matplotlib.lines import Line2D
    import matplotlib.pyplot as plt
    import numpy as np
    
    def rand_data():
        return np.random.uniform(low=0., high=1., size=(100,))
    
    # Generate data.
    x1, y1 = [rand_data() for i in range(2)]
    x2, y2 = [rand_data() for i in range(2)]
    
    plt.figure()
    plt.scatter(x1, y1, marker='o', label='first', s=20., c='b')
    plt.scatter(x2, y2, marker='o', label='second', s=35., c='r')
    
    # Create dummy Line2D objects for legend
    h1 = Line2D([0], [0], marker='o', markersize=np.sqrt(20), color='b', linestyle='None')
    h2 = Line2D([0], [0], marker='o', markersize=np.sqrt(20), color='r', linestyle='None')
    
    # Set axes limits
    plt.gca().set_xlim(-0.2, 1.2)
    plt.gca().set_ylim(-0.2, 1.2)
    
    # Plot legend.
    plt.legend([h1, h2], ['first', 'second'], loc="lower left", markerscale=2,
               scatterpoints=1, fontsize=10)
    plt.show()
    

    resulting figure

提交回复
热议问题