
author: 专注Python实战分享爬虫与数据分析干货title: Python爬虫实战㉒Matplotlib基础画出专业级数据图表update: 2026-04-26tags: Python,Matplotlib,可视化,折线图,柱状图,散点图,饼图,图表作者专注Python实战分享爬虫与数据分析干货更新时间2026年4月适合人群有Pandas基础、想让数据说话的开发者前言一图胜千言10万条数据堆在表格里老板看不懂。画成图表5秒理解。Matplotlib Python可视化的基石。所有高级图表库Seaborn、Pyecharts都基于它。一、基础配置1.1 安装与中文字体pipinstallmatplotlib-ihttps://pypi.tuna.tsinghua.edu.cn/simpleimportmatplotlib.pyplotaspltimportmatplotlib# 中文字体配置Windowsmatplotlib.rcParams[font.sans-serif][SimHei]# 黑体matplotlib.rcParams[axes.unicode_minus]False# 负号正常显示# 或者用微软雅黑matplotlib.rcParams[font.sans-serif][Microsoft YaHei]1.2 第一个图表importmatplotlib.pyplotasplt# 数据x[1,2,3,4,5]y[10,25,18,30,22]# 画图plt.figure(figsize(8,5))# 图表大小plt.plot(x,y)# 折线图plt.title(销售趋势)# 标题plt.xlabel(月份)# X轴标签plt.ylabel(销量)# Y轴标签plt.grid(True,alpha0.3)# 网格线plt.savefig(sales_trend.png,dpi150,bbox_inchestight)# 保存plt.show()二、常用图表类型2.1 折线图趋势importmatplotlib.pyplotaspltimportnumpyasnp months[f{i}月foriinrange(1,13)]sales_A[100,120,115,130,140,155,160,170,165,180,190,210]sales_B[80,95,90,100,110,120,125,135,130,145,150,165]plt.figure(figsize(10,6))plt.plot(months,sales_A,o-,label产品A,color#4472C4,linewidth2,markersize6)plt.plot(months,sales_B,s--,label产品B,color#ED7D31,linewidth2,markersize6)plt.title(月度销售趋势对比,fontsize16,fontweightbold)plt.xlabel(月份,fontsize12)plt.ylabel(销量,fontsize12)plt.legend(fontsize12)plt.grid(True,alpha0.3)plt.tight_layout()plt.savefig(line_chart.png,dpi150)plt.show()2.2 柱状图对比categories[手机,电脑,耳机,键盘,显示器]sales[450,320,580,290,210]colors[#4472C4,#ED7D31,#A5A5A5,#FFC000,#5B9BD5]plt.figure(figsize(8,5))barsplt.bar(categories,sales,colorcolors,width0.6,edgecolorwhite)# 添加数值标签forbar,valinzip(bars,sales):plt.text(bar.get_x()bar.get_width()/2,bar.get_height()10,str(val),hacenter,vabottom,fontsize12,fontweightbold)plt.title(各品类销量对比,fontsize16,fontweightbold)plt.ylabel(销量,fontsize12)plt.ylim(0,max(sales)*1.15)plt.tight_layout()plt.savefig(bar_chart.png,dpi150)plt.show()2.3 水平柱状图排名products[f产品{i}foriinrange(1,11)]valuessorted(np.random.randint(100,500,10))colorsplt.cm.RdYlGn(np.linspace(0.2,0.8,len(products)))plt.figure(figsize(8,6))plt.barh(products,values,colorcolors,height0.6)plt.title(产品销量排名,fontsize16,fontweightbold)plt.xlabel(销量,fontsize12)plt.tight_layout()plt.savefig(barh_chart.png,dpi150)plt.show()2.4 散点图相关性np.random.seed(42)pricenp.random.uniform(100,5000,100)sales1000-price*0.15np.random.normal(0,50,100)plt.figure(figsize(8,6))plt.scatter(price,sales,alpha0.6,c#4472C4,s50,edgecolorswhite)# 添加趋势线znp.polyfit(price,sales,1)pnp.poly1d(z)plt.plot(price,p(price),r--,linewidth2,labelf趋势线: y{z[0]:.2f}x{z[1]:.0f})plt.title(价格与销量关系,fontsize16,fontweightbold)plt.xlabel(价格,fontsize12)plt.ylabel(销量,fontsize12)plt.legend(fontsize12)plt.grid(True,alpha0.3)plt.tight_layout()plt.savefig(scatter_chart.png,dpi150)plt.show()2.5 饼图占比labels[手机,电脑,耳机,其他]sizes[35,25,20,20]colors[#4472C4,#ED7D31,#A5A5A5,#FFC000]explode(0.05,0,0,0)# 突出显示第一个plt.figure(figsize(8,8))plt.pie(sizes,explodeexplode,labelslabels,colorscolors,autopct%1.1f%%,startangle90,textprops{fontsize:14})plt.title(品类销售占比,fontsize16,fontweightbold)plt.tight_layout()plt.savefig(pie_chart.png,dpi150)plt.show()2.6 直方图分布np.random.seed(42)pricesnp.random.lognormal(mean7.5,sigma0.5,size1000)plt.figure(figsize(8,5))plt.hist(prices,bins30,color#4472C4,edgecolorwhite,alpha0.8)plt.axvline(np.mean(prices),colorred,linestyle--,labelf均值:{np.mean(prices):.0f})plt.axvline(np.median(prices),colorgreen,linestyle--,labelf中位数:{np.median(prices):.0f})plt.title(商品价格分布,fontsize16,fontweightbold)plt.xlabel(价格,fontsize12)plt.ylabel(数量,fontsize12)plt.legend(fontsize12)plt.tight_layout()plt.savefig(hist_chart.png,dpi150)plt.show()三、子图subplotfig,axesplt.subplots(2,2,figsize(12,10))# 子图1折线图axes[0,0].plot(months,sales_A,o-,color#4472C4)axes[0,0].set_title(月度趋势)# 子图2柱状图axes[0,1].bar(categories,sales,colorcolors)axes[0,1].set_title(品类对比)# 子图3散点图axes[1,0].scatter(price,sales,alpha0.5,c#4472C4)axes[1,0].set_title(价格-销量关系)# 子图4饼图axes[1,1].pie(sizes,labelslabels,colorscolors,autopct%1.1f%%)axes[1,1].set_title(品类占比)fig.suptitle(数据分析仪表板,fontsize18,fontweightbold)plt.tight_layout()plt.savefig(dashboard.png,dpi150)plt.show()四、知识卡图表类型函数适用场景折线图plt.plot()趋势变化柱状图plt.bar()类别对比水平柱状图plt.barh()排名散点图plt.scatter()相关性饼图plt.pie()占比直方图plt.hist()分布子图plt.subplots()多图组合五、课后作业必做题画出折线图展示月度趋势画柱状图对比不同类别画散点图分析两个变量的关系选做题用subplot制作4合1仪表板保存高清图片用于报告有问题欢迎评论区留言大家一起讨论标签Python | Matplotlib | 可视化 | 折线图 | 柱状图 | 散点图 | 饼图