爬虫数据可视化——爬下来的数据怎么展示才有说服力

📅 2026/6/30 5:26:51
爬虫数据可视化——爬下来的数据怎么展示才有说服力
数据爬下来了存到 Excel 或数据库里然后呢一堆数字不如一张图有说服力。这一篇讲怎么把爬虫数据变成可视化的图表用 matplotlib 做静态图、pyecharts 做交互图还有自动生成数据报告。一、matplotlib——静态图表pipinstallmatplotlib1. 柱状图商品价格对比importmatplotlib.pyplotaspltimportpandasaspd# 读取爬虫数据dfpd.read_excel(商品数据.xlsx)# 取前 10 个商品top10df.sort_values(price,ascendingFalse).head(10)# 设置中文字体plt.rcParams[font.sans-serif][SimHei,Microsoft YaHei]plt.rcParams[axes.unicode_minus]False# 创建画布plt.figure(figsize(12,6))# 画柱状图barsplt.bar(top10[title],top10[price])# 在柱子上标数字forbarinbars:heightbar.get_height()plt.text(bar.get_x()bar.get_width()/2.,height,f¥{height:.0f},hacenter,vabottom)plt.title(Top 10 商品价格对比)plt.xlabel(商品名称)plt.ylabel(价格元)plt.xticks(rotation45)# 标题太长就旋转plt.tight_layout()plt.savefig(商品价格对比图.png,dpi300)plt.show()2. 折线图价格走势# 假设爬取了某商品的历史价格dfpd.read_csv(价格历史.csv)df[date]pd.to_datetime(df[date])dfdf.sort_values(date)plt.figure(figsize(12,5))plt.plot(df[date],df[price],markero,linestyle-,linewidth2)# 标注最高点和最低点max_idxdf[price].idxmax()min_idxdf[price].idxmin()plt.annotate(f最高 ¥{df.loc[max_idx,price]:.0f},xy(df.loc[max_idx,date],df.loc[max_idx,price]),xytext(10,10),textcoordsoffset points,colorred)plt.annotate(f最低 ¥{df.loc[min_idx,price]:.0f},xy(df.loc[min_idx,date],df.loc[min_idx,price]),xytext(10,-15),textcoordsoffset points,colorgreen)plt.title(商品价格走势)plt.xlabel(日期)plt.ylabel(价格元)plt.grid(True,alpha0.3)plt.tight_layout()plt.savefig(价格走势图.png,dpi300)3. 饼图分类占比# 按分类统计商品数量category_countsdf[category].value_counts()colors[#ff6b6b,#ffd93d,#6bcb77,#4d96ff,#c9b1ff]plt.figure(figsize(8,8))plt.pie(category_counts.values,labelscategory_counts.index,autopct%1.1f%%,# 显示百分比startangle90,# 起始角度colorscolors[:len(category_counts)],explode[0.05]*len(category_counts),# 每块之间留空隙)plt.title(商品分类分布)plt.tight_layout()plt.savefig(分类占比.png,dpi300)4. 词云图评论关键词pipinstallwordcloudfromwordcloudimportWordCloud# 把所有评论文本拼起来comments_text .join(df[comment].dropna().tolist())# 生成词云wcWordCloud(font_pathC:/Windows/Fonts/simhei.ttf,# 中文字体路径width800,height600,background_colorwhite,max_words200,max_font_size80,).generate(comments_text)plt.figure(figsize(12,8))plt.imshow(wc,interpolationbilinear)plt.axis(off)plt.title(用户评论关键词云)plt.savefig(词云图.png,dpi300)plt.show()二、pyecharts——交互式图表pyecharts 生成的是 HTML 文件鼠标悬浮能看到数据、可以缩放、下载为图片。pipinstallpyecharts1. 交互式柱状图frompyecharts.chartsimportBarfrompyechartsimportoptionsasopts dfpd.read_excel(商品数据.xlsx)top10df.sort_values(price,ascendingFalse).head(10)bar(Bar().add_xaxis(top10[title].tolist()).add_yaxis(价格,top10[price].tolist()).set_global_opts(title_optsopts.TitleOpts(titleTop 10 商品价格),xaxis_optsopts.AxisOpts(axislabel_opts{rotate:45}),toolbox_optsopts.ToolboxOpts(),# 工具箱下载图片、缩放等).set_series_opts(label_optsopts.LabelOpts(formatter¥{c}),))bar.render(商品价格对比.html)print(已生成: 商品价格对比.html浏览器打开查看)2. 交互式折线图frompyecharts.chartsimportLine line(Line().add_xaxis(df[date].dt.strftime(%Y-%m-%d).tolist()).add_yaxis(价格,df[price].tolist()).set_global_opts(title_optsopts.TitleOpts(title价格走势),tooltip_optsopts.TooltipOpts(triggeraxis),datazoom_optsopts.DataZoomOpts(),# 缩放功能))line.render(价格走势.html)3. 地图数据的地理分布frompyecharts.chartsimportMap# 按省份统计数量province_countsdf[province].value_counts().reset_index()province_counts.columns[province,count]map_chart(Map().add(数量,[province_counts.values.tolist()],china).set_global_opts(title_optsopts.TitleOpts(title各省数据分布),visualmap_optsopts.VisualMapOpts(max_province_counts[count].max()),))map_chart.render(数据分布地图.html)三、自动生成数据报告把上面的图组合成一个 HTML 报告frompyecharts.chartsimportPage,Bar,Line,PiefrompyechartsimportoptionsasoptsclassCrawlerReport:爬虫数据报告生成器def__init__(self,df):self.dfdf self.pagePage(layoutPage.SimplePageLayout)defadd_price_bar(self):价格柱状图top10self.df.nlargest(10,price)bar(Bar().add_xaxis(top10[title].tolist()).add_yaxis(价格,top10[price].tolist()).set_global_opts(title_optsopts.TitleOpts(title价格 Top 10)))self.page.add(bar)defadd_category_pie(self):分类饼图dataself.df[category].value_counts()pie(Pie().add(,[list(z)forzinzip(data.index.tolist(),data.values.tolist())]).set_global_opts(title_optsopts.TitleOpts(title商品分类分布)).set_series_opts(label_optsopts.LabelOpts(formatter{b}: {d}%)))self.page.add(pie)defadd_stats_summary(self):统计摘要用表格展示statspd.DataFrame({指标:[商品总数,平均价格,最高价格,最低价格,品牌数量],数值:[len(self.df),f¥{self.df[price].mean():.2f},f¥{self.df[price].max():.2f},f¥{self.df[price].min():.2f},self.df[brand].nunique(),]})# pyecharts 不支持直接表格用 HTMLhtml_tablestats.to_html(indexFalse)frompyecharts.componentsimportTable tableTable()table.add(stats.columns.tolist(),stats.values.tolist())self.page.add(table)defgenerate(self,filename爬虫数据报告.html):生成完整报告self.add_stats_summary()self.add_price_bar()self.add_category_pie()# 可以继续加其他图表组件self.page.render(filename)print(f 报告已生成:{filename})# 使用dfpd.read_excel(商品数据.xlsx)reportCrawlerReport(df)report.generate()四、Kibana专业级可视化方案如果数据量很大几十万条以上并且你已经存到了 Elasticsearch直接用Kibana做可视化是最省事的——不用写代码拖拽配置就可以生成各种图表。五、不同场景的可视化推荐数据推荐图表适合展示商品价格柱状图价格对比价格趋势折线图历史走势分类占比饼图/环形图结构分布地域分布地图各省数据量评论内容词云图关键词热度评分分布箱线图异常值检测用户活跃度热力图时间分布规律六、让可视化更好看的三个技巧1. 配色不要用默认色# matplotlib 默认配色不太好看# 推荐配色方案colors[#5470C6,#91CC75,#FAC858,#EE6666,#73C0DE]# pyecharts 可以换主题frompyecharts.globalsimportThemeType barBar(init_optsopts.InitOpts(themeThemeType.CHALK))2. 图表标题和标注要清晰# 不要只写标题要让人一眼看懂plt.title(2026年上半年商品价格走势单位元)plt.xlabel(月份)plt.ylabel(价格)3. 数据量太大时要采样# 10 万条数据全画出来会一团黑# 采样展示sampledf.sample(n1000)# 随机取 1000 条plt.scatter(sample[price],sample[sales],alpha0.5)总结爬虫做得好不如展示得好 同类数据对比 → 柱状图 时间变化趋势 → 折线图 占比分布 → 饼图 地理位置 → 地图 文本分析 → 词云爬虫 可视化才是完整的数据采集方案——爬下来只是第一步能讲清楚数据背后的故事才是价值所在。 觉得有用的话点赞 关注【张老师技术栈】吧每周更新 Java/Python/爬虫 实战干货不让你白来。