【理论讲解】

数据分析不仅仅是数字,更需要“看得见”的洞察。数据可视化就是将数据转换成图表,帮助我们快速理解数据模式、趋势和异常。

  • Matplotlib: Python最基础、最灵活的绘图库。你可以用它画出各种静态图表,并对图表的每一个细节进行精细控制。
  • Seaborn: 基于Matplotlib的高级绘图库。它提供了更美观的图表样式和更丰富的统计图表类型,让你用更少的代码画出更漂亮的图。

【代码实例与电商场景案例】

我们将使用前面处理好的电商订单数据 df_orders 来进行可视化。

python

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# 设置中文显示和负号正常显示
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体为黑体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

# 加载电商订单数据 (假设已包含 total_amount 和 order_date)
df_orders = pd.read_csv('ecommerce_orders.csv')
df_orders['order_date'] = pd.to_datetime(df_orders['order_date'])
df_orders['total_amount'] = df_orders['price'] * df_orders['quantity']

print("用于可视化的订单数据预览:\n", df_orders.head())

# --- 3.1 Matplotlib基础 ---
print("\n--- Matplotlib基础绘图 ---")

# 电商场景:每日销售额折线图 (趋势分析)
daily_sales = df_orders.groupby('order_date')['total_amount'].sum()
plt.figure(figsize=(10, 6)) # 设置图表大小
plt.plot(daily_sales.index, daily_sales.values, marker='o', linestyle='-', color='skyblue') # 绘制折线图
plt.title('每日销售额趋势') # 设置标题
plt.xlabel('日期') # 设置X轴标签
plt.ylabel('销售额 (元)') # 设置Y轴标签
plt.grid(True) # 显示网格
plt.xticks(rotation=45) # X轴标签旋转45度
plt.tight_layout() # 调整布局,避免标签重叠
plt.show()

# 电商场景:商品类别销售额柱状图 (品类贡献分析)
category_sales = df_orders.groupby('category')['total_amount'].sum().sort_values(ascending=False)
plt.figure(figsize=(10, 6))
plt.bar(category_sales.index, category_sales.values, color='lightcoral') # 绘制柱状图
plt.title('各商品类别总销售额')
plt.xlabel('商品类别')
plt.ylabel('销售额 (元)')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

# 电商场景:支付方式占比饼图 (支付偏好分析)
payment_counts = df_orders['payment_method'].value_counts()
plt.figure(figsize=(8, 8))
plt.pie(payment_counts, labels=payment_counts.index, autopct='%1.1f%%', startangle=90, colors=sns.color_palette('pastel'))
plt.title('支付方式占比')
plt.axis('equal') # 使饼图为圆形
plt.show()

# 电商场景:商品价格分布散点图 (探索价格与数量关系)
plt.figure(figsize=(10, 6))
plt.scatter(df_orders['price'], df_orders['quantity'], alpha=0.7, color='green')
plt.title('商品价格与购买数量散点图')
plt.xlabel('商品单价 (元)')
plt.ylabel('购买数量')
plt.grid(True, linestyle='--', alpha=0.6)
plt.show()


# --- 3.2 Seaborn美化图表 ---
print("\n--- Seaborn美化与高级图表 ---")

# 设置Seaborn风格
sns.set_style("whitegrid") # 设置背景网格
sns.set_palette("muted") # 设置颜色板

# 电商场景:每日销售额折线图 (Seaborn版,更美观)
plt.figure(figsize=(10, 6))
sns.lineplot(x=daily_sales.index, y=daily_sales.values, marker='o')
plt.title('每日销售额趋势 (Seaborn)')
plt.xlabel('日期')
plt.ylabel('销售额 (元)')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

# 电商场景:商品类别销售额柱状图 (Seaborn版,更美观)
plt.figure(figsize=(10, 6))
sns.barplot(x=category_sales.index, y=category_sales.values)
plt.title('各商品类别总销售额 (Seaborn)')
plt.xlabel('商品类别')
plt.ylabel('销售额 (元)')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

# 电商场景:不同城市销售额对比 (箱线图 - 探索分布和异常)
plt.figure(figsize=(12, 7))
sns.boxplot(x='shipping_city', y='total_amount', data=df_orders)
plt.title('各城市订单总金额分布 (箱线图)')
plt.xlabel('收货城市')
plt.ylabel('订单总金额 (元)')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

# 电商场景:价格和数量的热力图 (探索高密度区域)
# 先对数据进行分组聚合,以便绘制热力图
price_qty_pivot = df_orders.pivot_table(index='price', columns='quantity', values='order_id', aggfunc='count').fillna(0)
plt.figure(figsize=(10, 8))
sns.heatmap(price_qty_pivot, cmap='viridis', annot=True, fmt=".0f", linewidths=.5)
plt.title('商品价格与购买数量热力图')
plt.xlabel('购买数量')
plt.ylabel('商品单价')
plt.tight_layout()
plt.show()

【互动问答】

  • Matplotlib和Seaborn在功能和使用上有哪些异同点?
  • 折线图、柱状图、饼图、散点图各自适用于什么类型的电商数据分析场景?
  • 箱线图能提供哪些关于数据分布的信息?在电商数据中,它能帮助我们发现什么?
  • 如何调整图表的标题、轴标签、字体大小和颜色?
  • 如果图表中的中文显示乱码,应该如何解决?(提示:plt.rcParams