在 Matplotlib 中,线性图(Line Plot) 是最基础的图表类型之一,用于展示数据随时间或其他连续变量的线性变化趋势。以下是详细的绘制方法和常见技巧,涵盖基础语法、样式定制、高级功能(如添加趋势线)等。
pythonimport matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.linspace(0, 10, 100) # 0到10的等分点(100个数据点)
y = 2 * x + 1 + np.random.randn(100) * 0.5 # 线性关系 + 噪声
# 创建图形和坐标轴
fig, ax = plt.subplots(figsize=(10, 6))
# 绘制线性图
ax.plot(x, y, marker='o', linestyle='-', linewidth=2, color='#2ecc71', markersize=5,
label='Linear Data')
# 添加基本元素
ax.set_xlabel('X轴标签', fontsize=12)
ax.set_ylabel('Y轴标签', fontsize=12)
ax.set_title('基础线性图示例', fontsize=14, pad=20)
ax.grid(True, linestyle='--', alpha=0.3)
# 显示图例
ax.legend(loc='upper left')
plt.tight_layout()
plt.show()
输出效果:
| 参数 | 作用 | 示例值 |
|---|---|---|
x | X轴数据(数组或列表) | np.linspace(0, 10, 100) |
y | Y轴数据(数组或列表) | 2 * x + 1 |
marker | 数据点标记(可选) | 'o', 's', '^' 等 |
linestyle | 线条样式(可选) | '-', '--', ':' 等 |
linewidth | 线条宽度(数值) | 2 |
color | 线条和标记颜色(颜色代码或名称) | '#2ecc71', 'red' |
markersize | 数据点大小(数值) | 5 |
label | 图例标签(可选) | 'Linear Data' |
使用 numpy.polyfit 或 scipy.stats.linregress 计算回归系数并绘制趋势线:
python# 计算线性回归
slope, intercept = np.polyfit(x, y, deg=1)
# 绘制回归线
ax.plot(x, slope * x + intercept, 'r--', linewidth=2,
label='Linear Regression: y={:.2f}x + {:.2f}'.format(slope, intercept))
python# 生成多组数据
x = np.linspace(0, 10, 100)
y1 = 2 * x + 1
y2 = 3 * x - 2
y3 = -x + 5
# 绘制多条线
ax.plot(x, y1, label='Line 1 (y=2x+1)')
ax.plot(x, y2, label='Line 2 (y=3x-2)', linestyle='--')
ax.plot(x, y3, label='Line 3 (y=-x+5)', linestyle=':')
自动调整坐标轴范围以适应数据:
pythonax.autoscale(enable=True, axis='both', tight=True)
• 线条样式:linestyle 参数支持 '-', '--', '-', ':' 等。
• 标记样式:marker 参数支持 'o', 's', 'D', '^' 等形状。
• 颜色映射:使用 cmap 参数为多条线分配颜色(需结合循环)。
原因:X轴数据未排序或包含缺失值。
解决:确保 x 数组是升序排列且无缺失值。
解决:使用 plt.tight_layout() 或 plt.subplots_adjust() 调整布局。
解决:通过 loc 参数调整图例位置(如 'upper left', 'lower right')。
python# 模拟股票数据
date = np.arange('2023-01-01', '2023-12-31', dtype='datetime64[D]')
price = 100 + np.cumsum(np.random.normal(0, 1, len(date)))
# 绘制价格走势
fig, ax = plt.subplots(figsize=(12, 6))
ax.plot(date, price, marker='.', linestyle='-', linewidth=1,
color='#3498db', label='Stock Price')
# 添加均线(20日移动平均)
window = 20
moving_avg = price.rolling(window=window).mean().dropna()
ax.plot(date[window:], moving_avg, 'g--', linewidth=2,
label='20-Day Moving Average')
ax.set_title('Stock Price Trend with Moving Average')
ax.set_xlabel('Date')
ax.set_ylabel('Price ($)')
ax.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
• 核心函数:ax.plot() 是绘制线性图的核心方法。
• 样式控制:通过参数调整线条、标记、颜色等,使图表更清晰易懂。
• 数据分析结合:可结合统计方法(如线性回归)增强图表的信息量。
• 布局优化:使用 tight_layout() 和 autopase 确保图表美观。