数据可视化入门
常用数据可视化工具与图表选择最佳实践。
图表选择指南
| 数据关系 | 推荐图表 | 适用场景 |
|---|---|---|
| 对比 | 柱状图、条形图 | 不同类别的数值比较 |
| 趋势 | 折线图、面积图 | 随时间变化的数据 |
| 占比 | 饼图、环形图、堆叠柱状图 | 部分与整体的关系 |
| 分布 | 直方图、箱线图 | 数据的分布形态 |
| 关系 | 散点图、气泡图 | 两个变量之间的相关性 |
| 地理 | 地图、热力图 | 基于地理位置的数据 |
Matplotlib 基础
python
import matplotlib.pyplot as plt
import numpy as np
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 基础折线图
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y1, label='sin(x)', color='#22c55e', linewidth=2)
ax.plot(x, y2, label='cos(x)', color='#3b82f6', linewidth=2)
ax.set_title('三角函数', fontsize=16)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
ax.grid(alpha=0.3)
plt.tight_layout()
plt.savefig('trig.png', dpi=150)
plt.show()Pandas 内置绑图
python
import pandas as pd
df = pd.DataFrame({
'月份': ['1月', '2月', '3月', '4月', '5月', '6月'],
'产量': [120, 135, 150, 142, 168, 175],
'良率(%)': [95.2, 96.1, 94.8, 97.0, 96.5, 97.3],
})
# 柱状图
df.plot(x='月份', y='产量', kind='bar', color='#22c55e', figsize=(8, 5))
plt.title('月度产量')
plt.tight_layout()
plt.show()Seaborn 统计图
python
import seaborn as sns
# 设置主题
sns.set_theme(style="darkgrid", palette="husl")
# 分布图
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
sns.histplot(data=df, x='产量', bins=10, kde=True, ax=axes[0])
axes[0].set_title('产量分布')
sns.boxplot(data=df, y='良率(%)', ax=axes[1])
axes[1].set_title('良率箱线图')
plt.tight_layout()
plt.show()Plotly 交互式图表
python
import plotly.express as px
# 交互式散点图
fig = px.scatter(
df, x='产量', y='良率(%)',
text='月份',
title='产量 vs 良率',
color_discrete_sequence=['#22c55e'],
)
fig.update_traces(textposition='top center', marker_size=12)
fig.show()
# 交互式折线图
fig = px.line(
df, x='月份', y='产量',
title='产量趋势',
markers=True,
)
fig.show()ECharts(前端方案)
适用于 Web 页面的交互式图表:
html
<div id="chart" style="width: 600px; height: 400px;"></div>
<script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
<script>
const chart = echarts.init(document.getElementById('chart'))
chart.setOption({
title: { text: '月度产量' },
xAxis: { data: ['1月', '2月', '3月', '4月', '5月', '6月'] },
yAxis: {},
series: [{
type: 'bar',
data: [120, 135, 150, 142, 168, 175],
itemStyle: { color: '#22c55e' },
}],
})
</script>可视化设计原则
- 数据墨水比:减少不必要的装饰,突出数据本身
- 颜色使用:同系列用渐变色,对比用互补色,不超过 7 种颜色
- 标注清晰:标题、轴标签、图例、数据标签缺一不可
- 响应式:考虑不同屏幕尺寸的展示效果
工具选择建议
- 快速探索:Pandas 内置 plot
- 精美静态图:Matplotlib + Seaborn
- 交互式图表:Plotly(Python)/ ECharts(前端)
- 商业报告:Power BI / Tableau