本文目录导读:

我来分享几个Python数据可视化的实用案例,涵盖不同类型的图表绘制:
准备工作
# 安装必要的库 # pip install matplotlib seaborn pandas numpy import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np # 设置中文显示 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
基础图表示例
1 折线图 - 展示趋势
# 示例数据:月度销售额
months = ['1月', '2月', '3月', '4月', '5月', '6月']
sales = [100, 120, 95, 140, 160, 155]
plt.figure(figsize=(10, 6))
plt.plot(months, sales, marker='o', linewidth=2, markersize=8, color='#2196F3')'2024年上半年销售额趋势', fontsize=16)
plt.xlabel('月份', fontsize=12)
plt.ylabel('销售额(万元)', fontsize=12)
plt.grid(True, alpha=0.3)
# 添加数据标签
for i, v in enumerate(sales):
plt.text(i, v+2, str(v), ha='center', va='bottom')
plt.tight_layout()
plt.show()
2 柱状图 - 比较数据
# 示例数据:各产品销量
products = ['产品A', '产品B', '产品C', '产品D', '产品E']
sales = [45, 32, 28, 51, 38]
plt.figure(figsize=(10, 6))
bars = plt.bar(products, sales, color=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7'])
# 自定义颜色
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']
for i, (bar, color) in enumerate(zip(bars, colors)):
bar.set_color(color)
plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
str(sales[i]), ha='center', va='bottom')
'各产品销量对比', fontsize=16)
plt.xlabel('产品', fontsize=12)
plt.ylabel('销量(件)', fontsize=12)
plt.tight_layout()
plt.show()
3 饼图 - 展示占比
# 示例数据:市场份额
labels = ['市场A', '市场B', '市场C', '市场D']
sizes = [35, 30, 20, 15]
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFEAA7']
explode = (0.1, 0, 0, 0) # 突出显示第一个扇区
plt.figure(figsize=(8, 8))
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)'市场份额分布', fontsize=16)
plt.axis('equal') # 确保饼图是圆的
plt.show()
高级图表示例
1 散点图 - 展示相关性
# 生成示例数据
np.random.seed(42)
n = 50
x = np.random.randn(n)
y = 2 * x + np.random.randn(n)
plt.figure(figsize=(10, 6))
scatter = plt.scatter(x, y, c=np.random.randn(n), s=100,
cmap='viridis', alpha=0.6)
# 添加趋势线
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x, p(x), "r--", alpha=0.8, label='趋势线')
plt.colorbar(scatter)'数据相关性分析', fontsize=16)
plt.xlabel('X值', fontsize=12)
plt.ylabel('Y值', fontsize=12)
plt.legend()
plt.tight_layout()
plt.show()
2 热力图 - 展示矩阵数据
# 创建相关性矩阵
data = pd.DataFrame(np.random.randn(100, 5),
columns=['特征A', '特征B', '特征C', '特征D', '特征E'])
correlation_matrix = data.corr()
plt.figure(figsize=(10, 8))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', center=0,
square=True, linewidths=1, cbar_kws={"shrink": 0.8})
'特征相关性热力图', fontsize=16)
plt.tight_layout()
plt.show()
3 箱线图 - 展示数据分布
# 示例数据
np.random.seed(42)
data = {
'组A': np.random.normal(100, 10, 100),
'组B': np.random.normal(90, 15, 100),
'组C': np.random.normal(110, 5, 100),
'组D': np.random.normal(95, 20, 100)
}
df = pd.DataFrame(data)
plt.figure(figsize=(12, 6))
sns.boxplot(data=df, palette='Set2')'各组数据分布对比', fontsize=16)
plt.xlabel('分组', fontsize=12)
plt.ylabel('数值', fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
实用技巧
1 子图布局
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
# 第一个子图:折线图
axes[0, 0].plot([1, 2, 3, 4], [1, 4, 2, 3])
axes[0, 0].set_title('折线图')
# 第二个子图:柱状图
axes[0, 1].bar(['A', 'B', 'C'], [3, 5, 2])
axes[0, 1].set_title('柱状图')
# 第三个子图:散点图
axes[1, 0].scatter([1, 2, 3, 4], [1, 4, 2, 3])
axes[1, 0].set_title('散点图')
# 第四个子图:饼图
axes[1, 1].pie([30, 40, 30], labels=['X', 'Y', 'Z'])
axes[1, 1].set_title('饼图')
plt.tight_layout()
plt.show()
2 保存图表
# 保存高清图片
plt.savefig('chart.png', dpi=300, bbox_inches='tight')
# bbox_inches='tight' 确保保存时不留白边
# 保存为PDF矢量格式
plt.savefig('chart.pdf', format='pdf', bbox_inches='tight')
数据可视化最佳实践
-
选择合适的图表类型:
- 趋势变化 → 折线图
- 数据比较 → 柱状图
- 数据分布 → 直方图/箱线图
- 相关性 → 散点图
- 占比 → 饼图
-
配色建议:
- 使用专业的配色方案(如ColorBrewer)
- 避免使用过多颜色
- 注意色盲友好配色
-
图表优化:
- 和轴标签
- 调整合适的图例位置
- 使用网格线辅助阅读
- 标注关键数据点
这些案例涵盖了常见的数据可视化需求,你可以根据实际数据特点选择合适的图表类型进行展示。