You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pandas从.csv文件绘制图表?含已有CSV数据的绘图问询

嘿,这问题我太熟了!用Pandas结合Matplotlib(Pandas默认依赖它做绘图后端)从CSV文件生成图表其实非常直观,我给你一步步拆解,连常见图表的例子都给你备好:

第一步:导入必备的库

首先得把Pandas和Matplotlib导入进来——前者负责读数据,后者负责把图表渲染出来:

import pandas as pd
import matplotlib.pyplot as plt
第二步:读取你的CSV文件

用pd.read_csv()加载你的数据文件,记得把路径换成你自己的CSV路径哦。加载完可以先打印前几行确认数据没读错:

# 替换成你的CSV文件路径,比如 './sales_data.csv'
df = pd.read_csv('your_data.csv')
# 查看前5行数据,确认加载成功
print(df.head())

如果你的CSV用的是分号、制表符这类特殊分隔符,可以加个参数:pd.read_csv('your_data.csv', sep=';')

第三步:绘制常见图表

Pandas的plot()方法能直接生成多种图表,下面是几个最常用的场景:

折线图(适合展示数据趋势)

如果你的数据是随时间或序列变化的,折线图是绝佳选择:

# 单条折线:绘制某一列的变化趋势
df['sales_amount'].plot(kind='line', figsize=(10, 6))
plt.title('Monthly Sales Trend')
plt.xlabel('Month Index')
plt.ylabel('Sales Amount')
plt.show()

# 多条折线对比:同时展示多列数据
df[['sales', 'expenses', 'profit']].plot(kind='line', figsize=(10, 6))
plt.title('Sales vs Expenses vs Profit')
plt.xlabel('Month')
plt.ylabel('Amount')
plt.legend()  # 显示图例
plt.show()

柱状图(适合对比类别数据)

用来展示不同类别之间的数值对比,或者统计频次:

# 频次柱状图:统计某类别列的出现次数
df['product_category'].value_counts().plot(kind='bar', figsize=(10, 6))
plt.title('Product Category Distribution')
plt.xlabel('Category')
plt.ylabel('Number of Sales')
plt.show()

# 分组柱状图:按类别分组,展示另一列的均值
df.groupby('region')['sales_amount'].mean().plot(kind='bar', figsize=(10, 6))
plt.title('Average Sales by Region')
plt.xlabel('Region')
plt.ylabel('Average Sales')
plt.show()

散点图(适合观察变量相关性)

想看两个数值变量之间有没有关联?用散点图就对了:

df.plot(kind='scatter', x='advertising_spend', y='sales_amount', figsize=(10, 6), color='darkorange')
plt.title('Advertising Spend vs Sales')
plt.xlabel('Advertising Spend ($)')
plt.ylabel('Sales Amount ($)')
plt.show()

直方图(查看数值数据的分布)

想知道某列数值的分布情况?直方图能帮你快速了解:

df['customer_age'].plot(kind='hist', bins=12, figsize=(10, 6))
plt.title('Customer Age Distribution')
plt.xlabel('Age')
plt.ylabel('Number of Customers')
plt.show()
几个实用小技巧
  • 如果数据里有缺失值,先处理一下:df.dropna()(删除缺失行)或者df.fillna(0)(用0填充),不然可能影响绘图
  • 想让图表更美观?可以导入Seaborn库,用sns.set()套用预设样式,Pandas的绘图会自动适配
  • 所有图表都可以通过figsize参数调整大小,color参数修改颜色,满足你的个性化需求

内容的提问来源于stack exchange,提问作者abhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:56:31