如何获取Matplotlib条形图中的所有条形?
要获取Matplotlib图表中的所有条形,我们可以使用 bar() 方法并返回各个条形。
步骤
- 设置图像大小并调整子图之间和周围的填充。
- 创建一个图像和一组子图。
- 使用 subplots() 方法创建 x 和 y 数据点。
- 制作条形图并将其存储在 bars 变量中。
- 设置特定一组条形的面颜色。
- 使用 show() 方法显示图像。
例子
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
x = np.arange(7)
y = np.random.rand(7)
bars = ax.bar(x, y, color='red')
bars[0].set_color('yellow')
bars[4].set_color('blue')
plt.show()