pythonmatplotlibscatter

How to display legend for matplotlib scatterplot color


I am plotting a two variable function on a 2d scatter plot, but I want to show a legend on what color on the scatter plot corresponds to what Z-value. Current code I have is below.

x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
z = [3, 8.5, 2.1, 1.8, 9]

fig1, ax1 = plt.subplots()
ax1.scatter(x, y, linewidths=1, alpha = .7, edgecolor= 'k', s=200, c=z)
plt.show()

Solution

  • Try this:

    import matplotlib.pyplot as plt
    
    x = [1, 2, 3, 4, 5]
    y = [1, 2, 3, 4, 5]
    z = [3, 8.5, 2.1, 1.8, 9]
    
    fig1, ax1 = plt.subplots()
    scat = ax1.scatter(x, y, linewidths=1, alpha = .7, edgecolor= 'k', s=200, c=z)
    ax1.legend(*scat.legend_elements(), title="Colors")
    
    plt.show()
    

    I tested this code in Python 3.10.4 with Matplotlib 3.5.2.

    I figured out this solution from the matplotlib documentation page, which has some other examples like this: https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/scatter_with_legend.html