一、数据准备与理解
1.1 模拟房价数据集
我们生成包含日期、价格、交易量的综合数据,模拟2010-2023年房价变化:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# 生成时间序列
dates = pd.date_range('2010-01', '2023-12', freq='ME')
n = len(dates)
# 生成趋势项(多项式趋势+周期性波动)
trend = np.linspace(100, 450, n) ** 1.1
seasonality = 50 * np.sin(np.linspace(0, 4*np.pi, n))
noise = np.random.normal(0, 15, n)
prices = trend + seasonality + noise
volume = np.random.lognormal(4, 0.3, n).astype(int)
# 创建DataFrame
df = pd.DataFrame({
'Date': dates,
'Price': prices.round(2),
'Volume': volume
}).set_index('Date')
1.2 数据概览
print(f"数据集维度:{df.shape}")
print(df.describe())
二、基础趋势可视化
2.1 绘制基础折线图
plt.figure(figsize=(14, 7))
# 主趋势线
main_line = plt.plot(df.index, df['Price'],
linestyle='-',
linewidth=2.5,
color='#2c7bb6',
marker='o',
markersize=5,
markerfacecolor='white',
markeredgewidth=1.5,
label='月度房价')
# 图表装饰
plt.title('2010-2023年房价趋势分析', fontsize=16, pad=20)
plt.xlabel('日期', fontsize=12, labelpad=10)
plt.ylabel('价格(万元/㎡)', fontsize=12, labelpad=10)
plt.grid(True, linestyle='--', alpha=0.7)
# 坐标轴格式化
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.gca().xaxis.set_major_locator(mdates.YearLocator())
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
三、增强可视化效果
3.1 添加关键标注
plt.figure(figsize=(16, 8))
# 绘制主趋势线
ax = plt.gca()
ax.plot(df.index, df['Price'], linewidth=2.5, color='#2c7bb6')
# 标注历史最高点
max_price = df['Price'].max()
max_date = df['Price'].idxmax()
ax.annotate(f'历史峰值:{max_price}万',
xy=(max_date, max_price),
xytext=(max_date - pd.DateOffset(years=2), max_price - 80),
arrowprops=dict(facecolor='red', shrink=0.05),
fontsize=10,
color='red')
# 添加趋势线
z = np.polyfit(mdates.date2num(df.index), df['Price'], 1)
p = np.poly1d(z)
ax.plot(df.index, p(mdates.date2num(df.index)),
'--',
color='orange',
label='长期趋势线')
# 突出政策调控期
ax.axvspan(pd.to_datetime('2016-10'), pd.to_datetime('2017-03'),
color='grey', alpha=0.2)
ax.text(pd.to_datetime('2016-11'), 300,
'限购政策实施',
rotation=90,
color='darkgrey')
# 设置双纵轴
ax2 = ax.twinx()
ax2.fill_between(df.index, df['Volume'],
color='green', alpha=0.1, label='交易量')
ax2.set_ylabel('月交易量(套)', fontsize=12)
plt.legend()
plt.show()
四、多维分析视图
4.1 复合图表分析
fig = plt.figure(figsize=(18, 10))
gs = fig.add_gridspec(2, 2)
# 主趋势区
ax1 = fig.add_subplot(gs[0, :])
ax1.plot(df['Price'], color='navy')
ax1.set_title('整体价格趋势', fontsize=14)
# 年度分布区
ax2 = fig.add_subplot(gs[1, 0])
year_groups = df.resample('YE').mean()
ax2.bar(year_groups.index.year, year_groups['Price'],
color='teal', alpha=0.7)
ax2.set_title('年度平均价格', fontsize=14)
# 季节波动区
ax3 = fig.add_subplot(gs[1, 1])
month_groups = df.groupby(df.index.month).mean()
ax3.plot(month_groups.index, month_groups['Price'],
marker='o', color='crimson')
ax3.set_title('月度季节波动', fontsize=14)
# 统一格式化
for ax in [ax1, ax2, ax3]:
ax.grid(True, linestyle=':', alpha=0.5)
ax.set_xlabel('')
plt.tight_layout()
plt.show()
五、高级可视化技巧
5.1 动态趋势图
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots(figsize=(12, 6))
line, = ax.plot([], [], lw=2)
ax.set_xlim(df.index[0], df.index[-1])
ax.set_ylim(df['Price'].min()-50, df['Price'].max()+50)
def animate(i):
data = df.iloc[:i+1]
line.set_data(data.index, data['Price'])
# 实时标注当前值
if i % 12 == 0:
ax.set_title(f'{data.index[i].year}年房价走势', fontsize=14)
return line,
ani = FuncAnimation(fig, animate, frames=len(df), interval=50)
plt.close()
六、专业图表优化
6.1 样式定制
plt.rcParams.update({
'font.family': 'SimHei', # 中文字体支持
'axes.titlesize': 14,
'axes.labelsize': 12,
'xtick.labelsize': 10,
'ytick.labelsize': 10,
'legend.fontsize': 10
})
# 保存高清图像
fig.savefig('price_trend.png',
dpi=300,
bbox_inches='tight',
facecolor='white')
关键分析结论
长期趋势:房价呈现指数级增长,年复合增长率约8.5%
季节规律:Q2季度普遍为交易旺季,价格上浮5-8%
政策影响:2016年限购政策后成交量下降40%,但价格仍保持上涨
市场周期:3-4年呈现明显波动周期,最近周期高点出现在2021年
进阶分析方向
价格预测:使用ARIMA/LSTM模型进行趋势预测
因素分析:结合GDP、利率等宏观经济指标进行回归分析
地理分异:按城市等级进行区域价格对比(需扩展数据集)
供需分析:结合库存去化周期指标进行市场健康度评估