如何使用 matplotlib 在一个图表中绘制多个水平条形图?


要使用 matplotlib 在一个图表中绘制多个水平条形图,我们可以执行以下步骤 −

步骤

  • 导入库 pandas、matplotlib 和 numpy。

  • 设置图形大小并调整子图之间的间距和子图周围的间距。

  • 创建水平条形图位置的数组。

  • 初始化条形图宽度的变量 width

  • 创建一个水平条形图。

  • 设置 Y 轴刻度和刻度标签,并设置一定的限制。

  • 在右上方的位置向图中添加图例。

  • 要显示图形,请使用 show() 方法。

示例

import pandas
import matplotlib.pyplot as plt
import numpy as np

# Set the figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Array for horizontal bar's position
ind = np.array([0, 1, 2])

# Bar's width
width = 0.4

fig, ax = plt.subplots()

# Horizontal bar plot
ax.barh(ind, np.array([4, 3, 5]), width, color='orange', label='N')
ax.barh(ind + width, np.array([2, 5, 2]), width, color='blue', label='M')

# Set Y-axis ticks and ticklabels
ax.set(yticks=ind + width, yticklabels=np.array(['A', 'B', 'C']),
ylim=[2*width - 1, len(ind)])

# Legend at the upper right corner
ax.legend(loc='upper right')

# Display the plot
plt.show()

输出

它将产生以下输出 −

更新时间: 2022 年 2 月 1 日

3000+ 浏览量

开启你的 职业之旅

完成课程后获得认证

开始
广告
© . All rights reserved.