0

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()
js23698
  • 3
  • 1

1 Answers1

0

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

datacoder
  • 66
  • 4
  • 1
    In this case, there is one legend, so there is no need to bother adding it to the artist. `ax1.legend(*scat.legend_elements(), title="Colors")` – r-beginners Jul 01 '22 at 01:43
  • @r-beginners, makes sense... will update answer. Thanks for catching that! – datacoder Jul 01 '22 at 02:45