数据可视化入门:用 Python 画出惊艳图表

数据可视化入门:用 Python 画出惊艳图表

数据可视化是把数字变成洞察的关键一步。同样的数据,不同的图表传达的信息截然不同。

本文用 Python 的 Matplotlib 和 Plotly 库,带你从零开始制作专业级别的图表。


环境准备

bash
pip install matplotlib seaborn plotly pandas numpy

| 库 | 用途 | 特点 |
|------|------|------|
| Matplotlib | 基础绘图 | 功能全面,配置灵活 |
| Seaborn | 统计图表 | 美观,语法简洁 |
| Plotly | 交互式图表 | 支持缩放和悬停 |
| Pandas | 数据处理 | 内置绘图接口 |

入门示例

折线图

python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.figure(figsize=(10, 6))
plt.plot(x, y1, label='sin(x)', linewidth=2, color='#e94560')
plt.plot(x, y2, label='cos(x)', linewidth=2, color='#0f3460')
plt.title('正弦和余弦曲线', fontsize=14, pad=15)
plt.xlabel('X 轴', fontsize=12)
plt.ylabel('Y 轴', fontsize=12)
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

柱状图

python
categories = ['Q1', 'Q2', 'Q3', 'Q4']
revenue = [120, 180, 160, 210]
profit = [30, 45, 40, 55]

x = range(len(categories))
width = 0.35

fig, ax = plt.subplots(figsize=(10, 6))
ax.bar([i - width/2 for i in x], revenue, width, label='收入', color='#16213e')
ax.bar([i + width/2 for i in x], profit, width, label='利润', color='#e94560')

ax.set_xlabel('季度')
ax.set_ylabel('金额(万元)')
ax.set_title('2025 年度收入和利润')
ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.legend()
plt.tight_layout()
plt.show()

Seaborn 统计图表

python
import seaborn as sns

tips = sns.load_dataset('tips')
sns.set_theme(style='whitegrid')

fig, axes = plt.subplots(2, 2, figsize=(14, 10))

sns.boxplot(data=tips, x='day', y='total_bill', ax=axes[0, 0])
axes[0, 0].set_title('每日小费分布')

sns.scatterplot(data=tips, x='total_bill', y='tip', hue='time', size='size', ax=axes[0, 1])
axes[0, 1].set_title('小费与账单金额关系')

corr = tips.select_dtypes(include=['float64', 'int64']).corr()
sns.heatmap(corr, annot=True, cmap='RdBu_r', ax=axes[1, 0])
axes[1, 0].set_title('特征相关性')

sns.violinplot(data=tips, x='day', y='total_bill', hue='sex', split=True, ax=axes[1, 1])
axes[1, 1].set_title('性别与消费分布')

plt.tight_layout()
plt.show()

Plotly 交互式图表

python
import plotly.express as px

df = px.data.gapminder()

fig = px.scatter(
    df.query("year == 2007"),
    x='gdpPercap', y='lifeExp',
    size='pop', color='continent',
    hover_name='country',
    log_x=True,
    title='2007 年各国 GDP 与预期寿命'
)
fig.show()

实战:销售仪表盘

python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

np.random.seed(42)
dates = pd.date_range('2025-01-01', '2025-12-31', freq='D')
sales = np.random.normal(1000, 200, len(dates))
sales += np.sin(np.arange(len(dates)) * 2 * np.pi / 365) * 300

df = pd.DataFrame({'date': dates, 'sales': sales})
df['month'] = df['date'].dt.month
df['weekday'] = df['date'].dt.day_name()

fig = plt.figure(figsize=(16, 10))
gs = GridSpec(2, 3, figure=fig)

ax1 = fig.add_subplot(gs[0, :])
monthly = df.groupby('month')['sales'].sum()
ax1.plot(monthly.index, monthly.values, marker='o', linewidth=2, color='#e94560')
ax1.set_title('月度销售趋势', fontsize=14)
ax1.grid(True, alpha=0.3)

weekday_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
ax2 = fig.add_subplot(gs[1, 0])
weekly = df.groupby('weekday')['sales'].mean().reindex(weekday_order)
colors = ['#16213e'] * 7
colors[4] = '#e94560'
ax2.bar(weekly.index, weekly.values, color=colors)
ax2.set_title('周内日平均销售额', fontsize=12)
ax2.tick_params(axis='x', rotation=45)

ax3 = fig.add_subplot(gs[1, 1])
ax3.hist(df['sales'], bins=30, color='#0f3460', edgecolor='white', alpha=0.7)
ax3.axvline(df['sales'].mean(), color='#e94560', linestyle='--', label=f'均值: {df["sales"].mean():.0f}')
ax3.set_title('销售额分布', fontsize=12)
ax3.legend()

plt.suptitle('2025 销售数据分析仪表盘', fontsize=18, y=1.02)
plt.tight_layout()
plt.show()

图表选择指南

| 目的 | 推荐图表 |
|------|---------|
| 趋势变化 | 折线图 |
| 比较分类 | 柱状图 |
| 分布情况 | 直方图、箱线图 |
| 相关性 | 散点图 |
| 占比 | 饼图(分类少) |
| 地理数据 | 地图 |
| 多变量 | 气泡图、热力图 |

美化技巧

python
plt.rcParams.update({
    'figure.facecolor': 'white',
    'axes.facecolor': '#fafafa',
    'axes.grid': True,
    'grid.alpha': 0.3,
    'axes.spines.top': False,
    'axes.spines.right': False,
    'font.size': 12,
    'axes.titlesize': 14,
})


数据可视化的核心不是炫技,而是让数据自己说话。选择合适的图表类型,保持设计简洁,重点数据用颜色突出。

推荐指数:⭐⭐⭐⭐⭐

在线资源:https://matplotlib.org/gallery/

💬 评论区 (0)

暂无评论,快来抢沙发吧!