如何在Python中更改 Matplotlib 颜色条大小?
颜色条是一个单独的轴,它提供一个当前的颜色图,指示数据点到颜色的映射。在本文中,我们将在Python中更改 Matplotlib 颜色条的大小。您可以通过多种方式调整颜色栏的大小或调整其位置。让我们一一看看。
方法 1:使用收缩关键字参数调整颜色条的大小
使用 colorbar()函数的收缩属性,我们可以缩放颜色条的大小。
Syntax : matplotlib.pyplot.colorbar(mappable=None, shrink=scale)
基本上,我们乘以某个因子到颜色条的原始大小。在下面的示例中,使用 0.5 作为因子,我们使用原始颜色条大小。
示例 1:
Python3
# importing library
import matplotlib.pyplot as plt
# Some data to show as an image
data = [[1, 2, 3],
[4, 5, 6]]
# Call imshow() to display 2-D data as an image
img = plt.imshow(data)
# Scaling colorbar by factor 0.5
plt.colorbar(shrink=0.5)
plt.show()
Python3
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
fig, ax = plt.subplots()
# getting rid of axis
plt.axis('off')
# Reading saved image from folder
img = mpimg.imread(r'img.jpg')
# displaying image
plt.imshow(img)
# Scaling by factor 0.75
plt.colorbar(shrink=0.75)
plt.show()
Python3
# importing libraries
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
# Reading image from folder
img = mpimg.imread(r'img.jpg')
image = plt.imshow(img)
# Locating current axes
divider = make_axes_locatable(ax)
# creating new axes on the right
# side of current axes(ax).
# The width of cax will be 5% of ax
# and the padding between cax and ax
# will be fixed at 0.05 inch.
colorbar_axes = divider.append_axes("right",
size="10%",
pad=0.1)
# Using new axes for colorbar
plt.colorbar(image, cax=colorbar_axes)
plt.show()
输出:
示例 2:在此示例中,我们使用因子 0.75。同样,您可以使用任何因素来更改颜色条大小。收缩属性的默认值为 1。
蟒蛇3
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
fig, ax = plt.subplots()
# getting rid of axis
plt.axis('off')
# Reading saved image from folder
img = mpimg.imread(r'img.jpg')
# displaying image
plt.imshow(img)
# Scaling by factor 0.75
plt.colorbar(shrink=0.75)
plt.show()
输出:
方法 2:使用 AxesDivider 类
使用此类,您可以更改颜色条轴的大小,但高度将与当前轴相同。在这里,我们使用axes_divider.make_axes_locatable函数,该函数返回显示图像的当前轴的AxisDivider 对象。
例子:
蟒蛇3
# importing libraries
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
# Reading image from folder
img = mpimg.imread(r'img.jpg')
image = plt.imshow(img)
# Locating current axes
divider = make_axes_locatable(ax)
# creating new axes on the right
# side of current axes(ax).
# The width of cax will be 5% of ax
# and the padding between cax and ax
# will be fixed at 0.05 inch.
colorbar_axes = divider.append_axes("right",
size="10%",
pad=0.1)
# Using new axes for colorbar
plt.colorbar(image, cax=colorbar_axes)
plt.show()
输出: