Python matplotlib 柱状图参数详解与实战

清欢
清欢
发布时间:2026-10-14| 3人浏览过
原创

本文基于 Python 3.6 及 Anaconda 环境,详细解析 matplotlib 库中 plt.bar() 函数的各项参数。通过加载 pandas 数据并逐步设置颜色、宽度、标签及字体等属性,展示如何绘制专业的柱状图。内容涵盖基础库导入、数据预处理及图表美化技巧,适合需要掌握数据可视化基础的用户参考。

运行环境版本为 python 3.6。

开发环境配置为 anaconda 结合 JupyterLab 0.27.0。

操作系统平台采用 Windows 10。


import pandas as pd
import matplotlib.pyplot as plt
a = pd.DataFrame(train_set['收率'].value_counts()).reset_index()
a.rename(columns={'index': 'yield','收率':'frequency'}, inplace=True)
a.head()
plt.figure(figsize=(24,8))
plt.bar(a['yield'].values,a['frequency'].values.round(2),color='rgb',width = 0.005,
tick_label=a['yield'].values.round(3))
plt.xlabel('yield', fontsize=20)
plt.ylabel('frequency', fontsize=20)
plt.show()

补充说明:本文重点讲解如何使用 python 的 matplotlib 库绘制柱状图,并详细解析 plt.bar() 函数的相关参数设置。

第一步,加载所需的 Python 库。


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

第二步进行绘图操作,逐步设置 bar() 函数的具体参数。


def title_table(ax):
    '''为图表添加标题和表格'''
    ax.set_title(label=f'No.{i+1}',
                loc='center',
                pad=None,
                fontdict={'color': 'b'}
                 )
    ax.table(loc='upper right',    # 表格在图表区的位置
          
          colLabels=[f'{i+2} args'],    # 表格每列的列名称
          colColours=['g'],    # 表格每列列名称所在单元格的填充颜色
          colLoc='left',    # 表格中每列列名称的对齐位置
          colWidths=[0.15],    # 表格每列的宽度         
          cellText=args,    # 表格中的数值, 每行数据的列表的列表
          cellColours=[['cornsilk']]*len(args),    # 表格中数据所在单元格的填充颜色
          cellLoc='left',    # 表格中数据的对齐位置
          fontsize=8)
# 配置字体,显示中文
mpl.rcParams['font.sans-serif'] = ['SimHei']  
# 配置坐标轴刻度值模式,显示负号
mpl.rcParams['axes.unicode_minus'] = True
# 定义数据
x = [1, 2, 3, 4, 5]
y = [6, 10, 4, 5, 1]
labels = list('ABCDE')
                   
fig, axes = plt.subplots(nrows=3,
                         ncols=3,
                         sharex=True,
                         sharey=True,
                         figsize=(18, 20),
                         facecolor='cornsilk')
axes = axes.ravel()
i = 0
ax = axes[i]
# 绘制柱状图
ax.bar(x=x,    # 柱体在 x 轴上的坐标位置
        height=y,    # 柱体的高度
       )
args = [[e] for e in ['x', 'height']]
# 向图表子区添加标题和数据表
title_table(ax)
i = 1
ax = axes[i]
# 绘制柱状图
ax.bar(x=x,    # 柱体在 x 轴上的坐标位置
        height=y,    # 柱体的高度
        align='edge',    #  x 轴上的坐标与柱体对其的位置
       )
args = [[e] for e in ['x', 'height', 'align']]
# 向图表子区添加标题和数据表
title_table(ax)
i = 2
ax = axes[i]
# 绘制柱状图
ax.bar(x=x,    # 柱体在 x 轴上的坐标位置
        height=y,    # 柱体的高度
        align='edge',    #  x 轴上的坐标与柱体对其的位置
        color='c',    # 柱体的填充颜色
        )
args = [[e] for e in ['x', 'height', 'align', 'color']]
# 向图表子区添加标题和数据表
title_table(ax)
i = 3
ax = axes[i]
# 绘制柱状图
ax.bar(x=x,    # 柱体在 x 轴上的坐标位置
        height=y,    # 柱体的高度
        align='edge',    #  x 轴上的坐标与柱体对齐的位置
        color='cyan',    # 柱体的填充颜色
        tick_label=labels,    # 每个柱体的标签名称
        )
args = [[e] for e in ['x', 'height', 'align', 'color', 'tick_label']]
# 向图表子区添加标题和数据表
title_table(ax)
i = 4
ax = axes[i]
# 绘制柱状图
ax.bar(x=x,    # 柱体在 x 轴上的坐标位置
        height=y,    # 柱体的高度
        align='edge',    #  x 轴上的坐标与柱体对其的位置
        color='blue',    # 柱体的填充颜色
        tick_label=labels,    # 每个柱体的标签名称
        alpha=0.6    # 柱体填充颜色的透明度
        )
args = [[e] for e in ['x', 'height', 'align', 'color', 'tick_label', 'alpha']]
# 向图表子区添加标题和数据表
title_table(ax)
i = 5
ax = axes[i]
# 绘制柱状图
ax.bar(x=x,    # 柱体在 x 轴上的坐标位置
        height=y,    # 柱体的高度
        align='edge',    #  x 轴上的坐标与柱体对其的位置
        color='wheat',    # 柱体的填充颜色
        tick_label=labels,    # 每个柱体的标签名称
        alpha=0.6,    # 柱体填充颜色的透明度
        width=1,  # 柱体的宽度
        )
args = [[e] for e in ['x', 'height', 'align', 'color', 'tick_label', 'alpha', 'width']]
# 向图表子区添加标题和数据表
title_table(ax)
i = 6
ax = axes[i]
# 绘制柱状图
ax.bar(x=x,    # 柱体在 x 轴上的坐标位置
        height=y,    # 柱体的高度
        align='edge',    #  x 轴上的坐标与柱体对其的位置
        color='aqua',    # 柱体的填充颜色
        tick_label=labels,    # 每个柱体的标签名称
        alpha=0.6,    # 柱体填充颜色的透明度
        width=0.8,    # 柱体的宽度
        bottom=0.2,     # 柱体基线的 y 轴坐标
        )
args = [[e] for e in ['x', 'height', 'align', 'color', 'tick_label', 'alpha', 'width',
                      'bottom']]
# 向图表子区添加标题和数据表
title_table(ax)
i = 7
ax = axes[i]
# 绘制柱状图
ax.bar(x=x,    # 柱体在 x 轴上的坐标位置
        height=y,    # 柱体的高度
        align='edge',    #  x 轴上的坐标与柱体对其的位置
        color='lightpink',    # 柱体的填充颜色
        tick_label=labels,    # 每个柱体的标签名称
        alpha=0.6,    # 柱体填充颜色的透明度
        width=0.8,    # 柱体的宽度
        bottom=0.2,    # 柱体基线的 y 轴坐标
        edgecolor='g'   # 柱体的边框颜色
        )
args = [[e] for e in ['x', 'height', 'align', 'color', 'tick_label', 'alpha', 'width',
                      'bottom', 'edgecolor']]
# 向图表子区添加标题和数据表
title_table(ax)
i = 8
ax = axes[i]
# 绘制柱状图
ax.bar(x=x,    # 柱体在 x 轴上的坐标位置
        height=y,    # 柱体的高度
        align='center',    #  x 轴上的坐标与柱体对其的位置
        color='bisque',    # 柱体的填充颜色
        tick_label=labels,    # 每个柱体的标签名称
        alpha=0.6,    # 柱体填充颜色的透明度
        width=0.8,    # 柱体的宽度
        bottom=0.2,    # 柱体基线的 y 轴坐标
        edgecolor='g',   # 柱体的边框颜色
        linewidth=1.5,   # 柱体边框线的宽度
        )
args = [[e] for e in ['x', 'height', 'align', 'color', 'tick_label', 'alpha', 'width',
                      'bottom', 'edgecolor', 'linewidth']]
# 向图表子区添加标题和数据表
title_table(ax)
# 设置整个子区的布局
fig.subplots_adjust(left=0,
                    bottom=0,
                    right=0.9,
                    top=1,
                    wspace=0.1,    # 子区间空白区域的宽度的归一化值
                    hspace=0.2);    # 子区间空白区域的高度的归一化值

最终生成的图表效果如下所示。

以上内容为个人经验总结,旨在为读者提供参考,欢迎大家支持本站。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。