别再死记硬背了!用Python Matplotlib画折线图、散点图、饼图的保姆级代码模板(附避坑点)
Python数据可视化实战Matplotlib黄金代码模板与避坑指南当你需要在周报中快速插入一张销售趋势折线图或是为实验数据生成直观的散点分布时Matplotlib往往是Python用户的首选工具。但面对繁杂的API文档和容易踩坑的参数设置很多开发者会陷入反复调试的困境。本文将提供五种最常用图表的即用型代码模板每个模板都经过实战检验并标注了新手最容易出错的配置项。1. 折线图趋势展示的基石折线图是展示时间序列或连续数据变化的标配。下面这个模板解决了三个常见痛点中文显示异常、图像尺寸失控和线条样式单调。import matplotlib.pyplot as plt import numpy as np # 解决中文显示问题 plt.rcParams[font.sans-serif] [SimHei] # Windows系统 plt.rcParams[axes.unicode_minus] False # 解决负号显示问题 # 生成示例数据 x np.linspace(0, 10, 100) y np.sin(x) # 黄金模板 fig, ax plt.subplots(figsize(8, 5)) # 单位是英寸 ax.plot(x, y, color#3498db, # 十六进制颜色码 linestyle--, # 虚线样式 linewidth2, # 线宽 markero, # 数据点标记 markersize5, # 标记大小 label正弦曲线) # 关键配置项 ax.set_title(月度销售额趋势, fontsize14) ax.set_xlabel(日期, fontsize12) ax.set_ylabel(销售额(万元), fontsize12) ax.grid(True, linestyle:, alpha0.7) # 网格线 ax.legend(locupper right) # 图例位置 plt.tight_layout() # 防止标签重叠 plt.savefig(line_chart.png, dpi300, bbox_inchestight) # 保存高清图 plt.show()避坑提示figsize参数的单位是英寸而非像素8×5的尺寸适合大多数报告。bbox_inchestight能自动裁剪白边避免保存时内容被截断。2. 散点图揭示数据关系的利器散点图在分析变量间相关性时不可或缺。这个模板解决了气泡图大小控制、颜色映射和透明度设置的难题。# 生成模拟数据 np.random.seed(42) x np.random.randn(100) y x * 2 np.random.randn(100) * 0.5 sizes np.abs(np.random.randn(100)) * 100 # 气泡大小 colors np.random.rand(100) # 颜色映射值 # 专业级散点图模板 fig, ax plt.subplots(figsize(8, 6)) scatter ax.scatter( x, y, ssizes, # 点的大小 ccolors, # 颜色值 cmapviridis, # 色谱方案 alpha0.7, # 透明度 edgecolorsw, # 边缘颜色 linewidths0.5 # 边缘线宽 ) # 高级配置 ax.set_title(用户年龄与消费金额关系, pad20) ax.set_xlabel(年龄, labelpad10) ax.set_ylabel(月均消费(元), labelpad10) # 添加颜色条 cbar fig.colorbar(scatter) cbar.set_label(消费频次, rotation270, labelpad15) # 添加趋势线 z np.polyfit(x, y, 1) p np.poly1d(z) ax.plot(x, p(x), r--, lw1.5) plt.tight_layout() plt.savefig(scatter_plot.png, dpi300) plt.show()常见问题解决方案点太小看不清调整s参数建议值50-200颜色区分不明显更换cmap为plasma或magma点重叠严重设置alpha0.5以下增加透明度3. 饼图比例展示的专业之道饼图虽然简单但要做到专业需要处理五个细节百分比显示、区块突出、颜色搭配、标签防重叠和起始角度。# 示例数据 labels [电子产品, 服装, 食品, 家居, 图书] sizes [15, 30, 45, 5, 5] explode (0, 0.1, 0, 0, 0) # 突出显示第二区块 colors [#ff9999,#66b3ff,#99ff99,#ffcc99,#c2c2f0] # 防呆模板 fig, ax plt.subplots(figsize(6, 6)) wedges, texts, autotexts ax.pie( sizes, explodeexplode, labelslabels, colorscolors, autopct%1.1f%%, startangle90, # 起始角度 counterclockFalse, # 顺时针方向 wedgeprops{linewidth: 1, edgecolor: white}, # 区块边框 textprops{fontsize: 10} ) # 美化百分比标签 for autotext in autotexts: autotext.set_color(white) autotext.set_weight(bold) # 添加中心空白实现甜甜圈效果 centre_circle plt.Circle((0,0), 0.7, fcwhite) fig.gca().add_artist(centre_circle) ax.set_title(季度销售额构成, y1.05) plt.savefig(pie_chart.png, dpi300, transparentTrue) # 透明背景 plt.show()专业建议当类别超过5个时考虑将小比例合并为其他项。使用transparentTrue保存的PNG图片能完美融入各种背景的PPT。4. 组合图表多维信息呈现将不同图表类型组合在同一画布上可以同时展示多个维度的信息。这个模板演示了如何创建带有折线图、柱状图和次坐标轴的复合图表。# 准备数据 months [1月, 2月, 3月, 4月, 5月, 6月] sales [23, 45, 56, 78, 55, 60] customers [120, 240, 300, 450, 320, 400] conversion [19.2, 18.8, 18.7, 17.3, 17.2, 15.0] # 创建画布和主坐标轴 fig, ax1 plt.subplots(figsize(10, 6)) # 柱状图主Y轴 bars ax1.bar( months, customers, color#3498db, alpha0.7, label客流量 ) ax1.set_ylabel(客流量人, fontsize12) ax1.tick_params(axisy) # 折线图次Y轴 ax2 ax1.twinx() line ax2.plot( months, sales, color#e74c3c, markero, linewidth2, label销售额 ) ax2.set_ylabel(销售额万元, fontsize12) # 第三个坐标轴共享X轴 ax3 ax1.twinx() ax3.spines[right].set_position((outward, 60)) # 偏移第三个Y轴 line2 ax3.plot( months, conversion, color#2ecc71, linestyle:, markers, linewidth2, label转化率(%) ) ax3.set_ylabel(转化率(%), fontsize12) # 合并图例 lines line line2 labels [l.get_label() for l in lines] ax1.legend(bars lines, [客流量] labels, locupper left, framealpha0.9) plt.title(上半年销售业绩分析, pad20) fig.tight_layout() plt.savefig(combo_chart.png, dpi300) plt.show()多图组合技巧使用twinx()创建共享X轴的新Y轴不同图表使用对比明显的颜色次坐标轴的位置可通过spines[right].set_position调整合并图例时注意顺序对应5. 高级样式配置从能用变好用让图表达到出版级质量需要关注以下细节配置这个模板封装了最常见的样式优化技巧。# 创建专业级样式配置 plt.style.use(seaborn) # 使用seaborn风格 # 示例数据 x np.arange(1, 6) y1 np.array([10, 20, 15, 25, 30]) y2 np.array([5, 15, 10, 20, 25]) # 初始化画布 fig, ax plt.subplots(figsize(9, 6)) # 绘制堆叠柱状图 bars1 ax.bar(x, y1, color#3498db, edgecolorwhite, linewidth1, label产品A) bars2 ax.bar(x, y2, bottomy1, color#e74c3c, edgecolorwhite, linewidth1, label产品B) # 高级文本标注 for rect in bars1 bars2: height rect.get_height() bottom rect.get_y() total_height height bottom ax.text(rect.get_x() rect.get_width()/2., total_height/2, f{int(height)}, hacenter, vacenter, colorwhite, fontsize10, fontweightbold) # 坐标轴美化 ax.spines[top].set_visible(False) ax.spines[right].set_visible(False) ax.spines[left].set_color(#95a5a6) ax.spines[bottom].set_color(#95a5a6) # 网格线配置 ax.grid(axisy, linestyle--, alpha0.4, color#7f8c8d) # 标题和标签 ax.set_title(产品销售额对比分析, pad20, fontsize14, fontweightbold) ax.set_xlabel(季度, labelpad10, fontsize12) ax.set_ylabel(销售额万元, labelpad10, fontsize12) # 刻度调整 ax.set_xticks(x) ax.set_xticklabels([Q1, Q2, Q3, Q4, Q5]) ax.tick_params(axisboth, whichboth, length0) # 图例位置优化 ax.legend(frameonTrue, locupper left, bbox_to_anchor(1, 1)) plt.tight_layout() plt.savefig(professional_chart.png, dpi300, quality95, optimizeTrue) plt.show()样式优化关键点使用plt.style.use()选择内置样式通过spines控制边框显示网格线使用浅色和透明度文本标注精确控制位置和样式保存时设置quality和optimize参数平衡文件大小和质量