matplotlib.pyplot.colorbar()函数

matplotlib.pyplot.colorbar()函数

颜色条是标量值到颜色映射的可视化。在Matplotlib中,它们被绘制成一个专用轴。

注意:Colorbar通常通过图.colorbar或它的pyplot包装器pyplot.colorbar创建,它在内部使用make_axes和Colorbar。作为终端用户,您很可能不需要显式地调用该模块中的方法或实例化该模块中的类。

在python中matplotlib.pyplot.colorbar()

matplotlib的pyplot模块中的colorbar()函数将一个colorbar添加到表示颜色比例的图形中。

语法:matplotlib.pyplot.colorbar(mapable =None, cax=None, ax=None, **kwarg)

参数:

ax:可选参数,包含“坐标轴”或“坐标轴列表”。

**kwarg(关键字参数):该参数是可选参数,有两种类型:

colorbar属性:

extend:{‘ neither ‘, ‘ both ‘, ‘ min ‘, ‘ max ‘}为超出范围的值设置尖端。

label:颜色条长轴上的标签。

ticks:无或ticks或Locator列表。

返回:colorbar,它是类“matplotlib.colorbar.colorbar”的一个实例。

下面的例子演示了matplotlib.pyplot.colorbar()函数在matplotlib.pyplot中的作用:

示例1

在散点图中添加水平颜色条。

# Python Program illustrating
# pyplot.colorbar() method
import numpy as np
import matplotlib.pyplot as plt
  
# Dataset
# List of total number of items purchased 
# from each products
purchaseCount = [100, 200, 150, 23, 30, 50,
                 156, 32, 67, 89]
  
# List of total likes of 10 products
likes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45]
  
# List of Like/Dislike ratio of 10 products
ratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56, 
         1.28, 1.09, 1.02]
  
# scatterplot
plt.scatter(x=purchaseCount, y=likes, c=ratio, cmap="summer")
  
plt.colorbar(label="Like/Dislike Ratio", orientation="horizontal")
plt.show()

输出:

matplotlib.pyplot.colorbar()函数

示例2

向多个子图添加一个颜色条。

# Python Program illustrating
# pyplot.colorbar() method
import matplotlib.pyplot as plt
  
# creates four Axes
fig, axes = plt.subplots(nrows=2, ncols=2)
  
for ax in axes.flat:
    im = ax.imshow(np.random.random((10, 10)), vmin=0, vmax=1)
  
plt.colorbar(im, ax=axes.ravel().tolist())
  
plt.show()

输出:

matplotlib.pyplot.colorbar()函数

示例3

为非映射对象添加颜色条。

# Python Program illustrating
# pyplot.colorbar() method
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
  
x = np.linspace(0, 5, 100)
N = 7
  
# colormap
cmap = plt.get_cmap('jet', N)
  
fig, ax1 = plt.subplots(1, 1, figsize=(8, 6))
  
for i, n in enumerate(np.linspace(0, 2, N)):
    y = x*i+n
    ax1.plot(x, y, c=cmap(i))
  
plt.xlabel('x-axis')
plt.ylabel('y-axis')
  
# Normalizer
norm = mpl.colors.Normalize(vmin=0, vmax=2)
  
# creating ScalarMappable
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
  
plt.colorbar(sm, ticks=np.linspace(0, 2, N))
  
  
plt.show()

输出:

matplotlib.pyplot.colorbar()函数

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程