数据可视化:Matplotlib、Seaborn与绑图基础
数据可视化:Matplotlib、Seaborn与绑图基础
数据可视化是数据分析的关键环节,能直观展示数据模式、趋势和关系。本文将介绍Python中最常用的可视化库:Matplotlib和Seaborn。
Matplotlib基础
Matplotlib是Python最基础的绑图库,几乎所有可视化库都建立在它之上:
import matplotlib.pyplot as plt
import numpy as np
# 基础绑图
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(10, 6))
plt.plot(x, y, label='sin(x)', color='blue', linewidth=2)
plt.plot(x, np.cos(x), label='cos(x)', color='red', linestyle='--')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('正弦和余弦函数')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
常用绑图类型
绑图与柱状图
import matplotlib.pyplot as plt
import numpy as np
# 简单柱状图
categories = ['电子', '服装', '食品', '家居', '图书']
values = [350, 280, 180, 220, 150]
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# 垂直柱状图
axes[0].bar(categories, values, color=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7'])
axes[0].set_title('各品类销售额')
axes[0].set_ylabel('销售额(万元)')
# 水平柱状图
axes[1].barh(categories, values, color=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7'])
axes[1].set_title('各品类销售额(水平)')
plt.tight_layout()
plt.show()
散点图
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
x = np.random.randn(100)
y = 2 * x + np.random.randn(100) * 0.5
colors = np.random.rand(100)
sizes = np.abs(x) * 200 + 50
plt.figure(figsize=(10, 6))
scatter = plt.scatter(x, y, c=colors, s=sizes, alpha=0.6, cmap='viridis')
plt.colorbar(scatter, label='颜色值')
plt.xlabel('X值')
plt.ylabel('Y值')
plt.title('带颜色和大小的散点图')
plt.grid(True, alpha=0.3)
plt.show()
饼图与环形图
import matplotlib.pyplot as plt
# 饼图
labels = ['电子', '服装', '食品', '家居', '其他']
sizes = [35, 28, 18, 12, 7]
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']
explode = (0.1, 0, 0, 0, 0)
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
plt.title('销售占比')
# 环形图
plt.subplot(1, 2, 2)
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%',
pctdistance=0.85, startangle=90)
# 添加中心圆
centre_circle = plt.Circle((0, 0), 0.70, fc='white')
plt.gca().add_artist(centre_circle)
plt.title('销售占比(环形)')
plt.tight_layout()
plt.show()
Seaborn统计可视化
Seaborn基于Matplotlib,提供更美观的统计图表:
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 设置风格
sns.set_theme(style="whitegrid")
# 创建示例数据
np.random.seed(42)
df = pd.DataFrame({
'类别': np.random.choice(['A', 'B', 'C'], 100),
'数值': np.random.randn(100).cumsum(),
'分组': np.random.choice(['组1', '组2'], 100)
})
# 分布图
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# 直方图
sns.histplot(data=df, x='数值', hue='类别', kde=True, ax=axes[0, 0])
axes[0, 0].set_title('数值分布(直方图+KDE)')
# 箱线图
sns.boxplot(data=df, x='类别', y='数值', hue='分组', ax=axes[0, 1])
axes[0, 1].set_title('分组箱线图')
# 小提琴图
sns.violinplot(data=df, x='类别', y='数值', hue='分组', split=True, ax=axes[1, 0])
axes[1, 0].set_title('小提琴图')
# 热力图
corr_matrix = df['数值'](/notes/).assign(类别编码=df['类别'].map({'A': 1, 'B': 2, 'C': 3})).corr()
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', ax=axes[1, 1], vmin=-1, vmax=1)
axes[1, 1].set_title('相关性热力图')
plt.tight_layout()
plt.show()
高级绑图技巧
import matplotlib.pyplot as plt
import numpy as np
# 子图布局
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
fig.suptitle('多子图展示', fontsize=16)
# 不同类型的图
x = np.linspace(0, 2 * np.pi, 100)
axes[0, 0].fill_between(x, np.sin(x), alpha=0.3)
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title('填充图')
axes[0, 1].stackplot(range(5), [1, 2, 3, 2, 4], [2, 3, 1, 4, 2])
axes[0, 1].set_title('堆叠图')
axes[0, 2].bar(range(5), [3, 1, 4, 1, 5], color='skyblue')
axes[0, 2].set_title('柱状图')
axes[1, 0].scatter(np.random.randn(20), np.random.randn(20), s=100, alpha=0.6)
axes[1, 0].set_title('散点图')
axes[1, 1].pie([30, 20, 50], labels=['A', 'B', 'C'], autopct='%1.1f%%')
axes[1, 1].set_title('饼图')
data = np.random.rand(8, 8)
axes[1, 2].imshow(data, cmap='viridis')
axes[1, 2].set_title('热力图')
plt.tight_layout()
plt.show()
交互式可视化
import plotly.express as px
import pandas as pd
# 使用Plotly创建交互式图表
df = pd.DataFrame({
'月份': ['1月', '2月', '3月', '4月', '5月', '6月'],
'销售额': [100, 120, 110, 130, 140, 150],
'利润': [20, 25, 22, 28, 30, 35]
})
# 交互式折线图
fig = px.line(df, x='月份', y=['销售额', '利润'], title='月度趋势')
fig.show()
# 交互式柱状图
fig = px.bar(df, x='月份', y='销售额', color='利润', title='销售额分布')
fig.show()
实战:销售数据可视化
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# 创建销售数据
np.random.seed(42)
months = ['1月', '2月', '3月', '4月', '5月', '6月']
products = ['手机', '电脑', '平板']
data = {
'月份': months * 3,
'产品': np.repeat(products, 6),
'销量': np.random.randint(50, 200, 18),
'单价': [3000, 3000, 3000, 3000, 3000, 3000,
6000, 6000, 6000, 6000, 6000, 6000,
2000, 2000, 2000, 2000, 2000, 2000]
}
df = pd.DataFrame(data)
df['销售额'] = df['销量'] * df['单价']
# 创建综合图表
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle('销售数据分析仪表板', fontsize=16)
# 1. 产品销量趋势
for product in products:
mask = df['产品'] == product
axes[0, 0].plot(df[mask]['月份'], df[mask]['销量'], marker='o', label=product)
axes[0, 0].set_title('产品销量趋势')
axes[0, 0].legend()
axes[0, 0].grid(True, alpha=0.3)
# 2. 产品销售额占比
product_sales = df.groupby('产品')['销售额'].sum()
axes[0, 1].pie(product_sales.values, labels=product_sales.index, autopct='%1.1f%%')
axes[0, 1].set_title('产品销售额占比')
# 3. 月度总销售额
monthly_sales = df.groupby('月份')['销售额'].sum()
axes[1, 0].bar(monthly_sales.index, monthly_sales.values, color='steelblue')
axes[1, 0].set_title('月度总销售额')
axes[1, 0].tick_params(axis='x', rotation=45)
# 4. 销量与单价关系
axes[1, 1].scatter(df['单价'], df['销量'], c='coral', s=100, alpha=0.7)
axes[1, 1].set_title('销量与单价关系')
axes[1, 1].set_xlabel('单价')
axes[1, 1].set_ylabel('销量')
plt.tight_layout()
plt.show()
总结
数据可视化是数据科学的重要技能。Matplotlib提供底层控制,Seaborn提供美观的统计图表,Plotly提供交互式体验。根据需求选择合适的工具,能让你的数据故事更加生动有力。