【问题标题】:How to use colormap in this matplotlib plot?如何在这个 matplotlib 图中使用颜色图?
【发布时间】:2018-12-28 22:51:36
【问题描述】:

我正在尝试向此 matplotlib 绘图添加颜色图(代码如下)。我使用了颜色渐变来说明运动在时间或步骤中的进展(色调是时间或 n 的函数)。现在我想在图中的插图中添加一个颜色图,但我无法成功。

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()

我正在寻找的是绘图右侧的颜色条,其比例从 0 到 5000 均分。

【问题讨论】:

    标签: python matplotlib colormap


    【解决方案1】:

    您需要将轴句柄提供给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()
    

    【讨论】:

    • 正是我想要的。非常感谢。
    猜你喜欢
    • 2019-03-23
    • 2021-09-11
    • 1970-01-01
    • 2018-02-28
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多