简体   繁体   English

如何在 matplotlib 中添加颜色条

[英]How to add colorbar in matplotlib

I don't really understand the documentation on colorbar I wanted explanation on a basic example.我不太了解 colorbar 上的文档,我想对一个基本示例进行解释。 So below I am plotting exp(-x*a) for a={1, 2, 3, 4}.所以下面我为 a={1, 2, 3, 4} 绘制 exp(-x*a)。 How do I add color bar with the values of a.如何使用 a 的值添加颜色条。

import numpy as np
import matplotlib.pyplot as plt

def func(x,a):
    return np.exp(-x*a)
x = np.linspace(0, 5)

for a in range(1,5):
    plt.plot(func(x,a))
plt.show()

I'm confused with imshow, subplot, ax.我对 imshow、subplot、ax 感到困惑。

Colour schemes are defined in the range 0 to 1, therefore you first need to normalise your values (0 to 5) to the range 0 to 1. Then you can pull the colour from the colormap.颜色方案定义在 0 到 1 的范围内,因此您首先需要将值(0 到 5)标准化为 0 到 1 的范围。然后您可以从颜色图中提取颜色。 At the end you have to plot a color bar using the colour map and norm that you chose on the axis you used for plotting.最后,您必须使用颜色 map 和您在用于绘图的轴上选择的标准 plot 一个颜色条。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm, colors


def func(x, a):
    return np.exp(-x * a)


x = np.linspace(0, 5)

fig, ax = plt.subplots()

# define color map
cmap = cm.get_cmap("Spectral")

# need to normalize because color maps are defined in [0, 1]
norm = colors.Normalize(0, 5)

for a in range(1, 5):
    ax.plot(x, func(x, a), 
        color=cmap(norm(a)))  # get color from color map 

# plot colorbar
fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)

plt.show()

The plot looks like this: plot 看起来像这样: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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