Q:

Python scatterplot with variable marker color and size, plus a legend

I want to create a scatterplot from x and y with the following features :

marker size variable (according to a value z that
corresponds to the pair (x,y))
marker color variable (according to a category c that corresponds to the pair (x,y))
including a legend that shows the different values of c and how they're matched to a color

I have found many answers as to how to combine 2 out of these 3 requirements. However, I haven't seen them all implemented jointly, neither on seaborn nor on matplotlib.

A:

You set the marker size using the s kwarg to ax.scatter.
You set the marker colour using the c kwarg to ax.scatter.
You can add a colorbar to show how colour maps to the c array.

For example:
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1)

# Some fake data
X, Y = np.meshgrid(np.arange(0.5, 10), np.arange(0.5, 10))
X = X.flatten()
Y = Y.flatten()
c = np.random.rand(X.size)
z = np.random.rand(X.size)*100

# Plot using scatter. Color use 'c' kwarg. Set size using 's' kwarg.
p = ax.scatter(X, Y, c=c, s=z, cmap='viridis', vmin=0, vmax=1)

# Add a colorbar
fig.colorbar(p)

plt.show()

