在 Matplotlib 中显示颜色条
Manav Narula
2021年7月4日

在本教程中,我们将讨论如何在 Python 中的 matplotlib 图形中显示颜色条。
要创建颜色条,我们必须使用 matplotlib.pyplot.colorbar()
函数。
下面的代码显示了一个简单的例子。
import random
import matplotlib.pyplot as plt
s_x = random.sample(range(0, 100), 20)
s_y = random.sample(range(0, 100), 20)
s = plt.scatter(s_x, s_y, c=s_x, cmap="viridis")
c = plt.colorbar()
在上面的示例中,我们创建了一个放置在绘图之外的简单颜色条。我们使用 cmap
参数指定了颜色图。
我们还可以指定我们希望显示颜色条的轴。如果我们愿意,我们可以将它添加到绘图的轴上。
例如,
import random
import matplotlib.pyplot as plt
s_x = random.sample(range(0, 100), 20)
s_y = random.sample(range(0, 100), 20)
fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
im = ax.scatter(s_x, s_y, c=s_x, cmap="viridis")
fig.colorbar(im, cax=cax, orientation="horizontal")
在上面的示例中,我们使用 subplots()
函数来获取图形和轴对象,并使用它来创建颜色条的轴。我们使用 colorbar()
函数中的 cax
参数指定了这一点。
另外,请注意 orientation
参数的使用,它改变了最终颜色条的方向。除此之外,我们可以使用不同的参数来控制颜色条的形状和大小。例如,shrink
可以将颜色条的大小缩小一小部分,aspect
,这是条边的比例,还有更多。
作者: Manav Narula
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn