数据可视化入门:用Matplotlib画出让人眼前一亮的图表
数据可视化是数据科学中最"出片"的环节。本文教你用Python画出专业又好看的图表。
一图胜千言
在数据科学领域,一张好图 > 一千行代码。
Matplotlib 基础
import matplotlib.pyplot as plt
import numpy as np
# 简单的折线图
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("正弦波")
plt.xlabel("时间")
plt.ylabel("振幅")
plt.show()让图表更好看的技巧
1. 配色方案
不要用默认配色!用这些:
plt.style.use("seaborn-v0_8")plt.style.use("ggplot")plt.style.use("fivethirtyeight")
2. 字体设置
plt.rcParams["font.family"] = "sans-serif"
plt.rcParams["font.size"] = 123. 添加注释
plt.annotate("最高点", xy=(x[peak], y[peak]),
xytext=(x[peak]+0.5, y[peak]+0.5),
arrowprops=dict(arrowstyle="->"))三种最常用的图表
折线图 — 展示趋势
适合:股票价格、温度变化、网站流量
柱状图 — 对比大小
适合:各月销售额、不同类别数量
散点图 — 看相关性
适合:身高体重关系、广告费与销售额
实战:画一个漂亮的仪表盘
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
# 左上:折线图
axes[0, 0].plot(dates, sales)
axes[0, 0].set_title("月度销售趋势")
# 右上:柱状图
axes[0, 1].bar(categories, values)
axes[0, 1].set_title("各品类销量")
# 左下:散点图
axes[1, 0].scatter(ad_spend, revenue, alpha=0.6)
axes[1, 0].set_title("广告费 vs 收入")
# 右下:饼图
axes[1, 1].pie(sizes, labels=labels, autopct="%1.1f%%")
axes[1, 1].set_title("市场份额")
plt.tight_layout()
plt.show()推荐的工具
- Matplotlib — 基础,必学
- Seaborn — 基于 Matplotlib,更美观
- Plotly — 交互式图表
- Tableau — 拖拽式,非程序员友好
好的数据可视化不是把数据画出来,而是讲一个故事。你的图表应该让读者在 3 秒内看懂你想表达什么。