1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import matplotlib.pyplot as plt import numpy as np
# 自定义x轴标签 x_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
# 数据 categories = ['Category 1', 'Category 2', 'Category 3', 'Category 4', 'Category 5'] values = np.array([[15, 25, 35, 45, 55], [20, 30, 40, 50, 60], [25, 35, 45, 55, 65], [30, 40, 50, 60, 70], [35, 45, 55, 65, 75]])
# 设置每个柱形的宽度和间隔 bar_width = 0.15 month_gap = 0.3 # 月份之间的间隔 bar_positions = np.arange(len(x_labels)) * (len(categories) * bar_width + month_gap)
# 绘图 for i, category in enumerate(categories): plt.bar(bar_positions + i * bar_width, values[i], width=bar_width, label=category)
# 添加标题和标签 plt.title('Monthly Comparison Bar Chart') plt.xlabel('Months') plt.ylabel('Values') plt.xticks(bar_positions + (len(categories) - 1) * bar_width / 2, x_labels) # 设置x轴刻度标签,并居中对齐
# 添加图例 plt.legend()
# 显示图形 plt.show()
|