文章目录
1. 单柱柱形图
绘制单柱柱形图较为简单,轻松调用plt.bar()方法就可以实现。下边展示一段绘制一幅具有更多细节的单柱形图的代码即图像。
import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.rcParams['axes.facecolor'] ='#cc00ff' x = ['A型', 'B型', 'C型', 'D型', 'E型', 'F型'] height = [320, 410, 460, 550, 670, 800] plt.xlabel('型号') plt.ylabel('X指标值') plt.title('某产品不同型号X指标分析图') plt.grid(axis="y", which="major") plt.bar(x, height, color='#6600ff') for a, b in zip(x, height): plt.text(a, b, format(b, ','), ha='center', va='bottom', fontsize=12, color='r') plt.legend(["X指标"]) plt.show()
2. 多柱柱形图
绘制多柱柱形图,即确定好柱的宽度width,然后错位分批进行绘制。因为x要参与与width的运算,所以建议绘图的时候使用数值型的x来取代原数据中的x,然后再用xticks将其替代回来即可。
import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.rcParams['axes.facecolor'] ='#cc00ff' x_ticks = ['2016', '2017', '2018', '2019', '2020', '2021'] x = range(len(x_ticks)) plt.xticks(x, x_ticks) height_A = [320, 410, 460, 550, 670, 800] height_B = [300, 440, 500, 580, 690, 770] height_C = [400, 450, 523, 700, 820, 840] height_D = [390, 460, 530, 650, 740, 900] width = 0.2 plt.xlabel('型号') plt.ylabel('X指标值') plt.title('某产品不同型号X指标分析图') plt.grid(axis="y", which="major") x_array = np.array(x) plt.bar(x_array, height_A, color='#6600ff', width=width) plt.bar(x_array + width, height_B, color='#ffff00', width=width) plt.bar(x_array + 2 * width, height_C, color='#ff0000', width=width) plt.bar(x_array + 3 * width, height_D, color='#33ff33', width=width) for a, b in zip(x, height_A): plt.text(a, b, format(b, ','), ha='center', va='bottom', fontsize=12, color='#6600ff') for a, b in zip(x, height_B): plt.text(a + width, b, format(b, ','), ha='center', va='bottom', fontsize=12, color='#ffff00') for a, b in zip(x, height_C): plt.text(a + 2 * width, b, format(b, ','), ha='center', va='bottom', fontsize=12, color='#ff0000') for a, b in zip(x, height_D): plt.text(a + 3 * width, b, format(b, ','), ha='center', va='bottom', fontsize=12, color='#33ff33') plt.legend(["A型", 'B型', 'C型', 'D型']) plt.show()