单柱柱形图与多柱柱形图的绘制 基于python-matplotlib库

58 阅读2分钟

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')

在这里插入图片描述

感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的:

① 2000多本Python电子书(主流和经典的书籍应该都有了)

② Python标准库资料(最全中文版)

③ 项目源码(四五十个有趣且经典的练手项目及源码)

④ Python基础入门、爬虫、web开发、大数据分析方面的视频(适合小白学习)

⑤ Python学习路线图(告别不入流的学习)

了解详情:docs.qq.com/doc/DSnl3ZG…