简体   繁体   中英

How to use colormap in this matplotlib plot?

I am trying to add a colormap to this matplotlib plot (code below). I have used a gradient of color to illustrate the progression of the motion in time or steps (the hue is a function of time or n). Now I want to add a colormap in the inset of the figure and I am not able to succeed.

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot') 
n = 5000
x = np.cumsum(np.random.randn(n))
y = np.cumsum(np.random.randn(n))
# We add 10 intermediary points between two successive points. We 
# interpolate x and y.
k = 10
x2 = np.interp(np.arange(n * k), np.arange(n) * k, x)
y2 = np.interp(np.arange(n * k), np.arange(n) * k, y)
fig, ax = plt.subplots(1, 1, figsize=(8, 8))
# Now, we draw our points with a gradient of colors.
ax.scatter(x2, y2, c=range(n * k), linewidths=0, marker='o', s=3, 
cmap=plt.cm.jet,)
ax.axis('equal')
ax.set_axis_off()

What I am looking for is a colorbar on the right-hand side of the plot with evenly divided scales from 0 to 5000.

You need to provide the axis handle to the colorbar

ax_ = ax.scatter(x2, y2, c=range(n * k), linewidths=0, marker='o', s=3, cmap=plt.cm.jet,) # <---- store plot instance in ax_
ax.axis('equal')

plt.colorbar(ax_) # <--- here provide ax_ (can choose other name as well)
ax.set_axis_off()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM