The Colorbar for Scatter Plots
Some time ago we were talking about scatter plots. In the previous article we were talking about colorbars. In this article we’ll use a colorbar for the colors of the points.
Let’s start by creating a scatter plot. The points will be circles differing in color and size:
In [2]:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(10, 50, 100)
# Let's randomize the position of Y values.
a = np.random.randn(100)
y = x * a
# Let's set alpha to 0.5. The size and color will depend on the value of Y.
fig, ax = plt.subplots()
ax.scatter(x, y, marker='o', alpha=.5, s=y*50, c=y)
Out[2]:
Now we have a nice scatter plot. All we need to do is add the legend. Let’s create a colorbar then:
In [3]:
fig, ax = plt.subplots()
# Let's assign the scatter plot to a variable.
p = ax.scatter(x, y, marker='o', alpha=.5, s=y*50, c=y)
# Now we can use the variable to create the colorbar.
fig.colorbar(p)
Out[3]: