import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# 示例数据
data = {
'x': np.random.randn(100),
'y': np.random.randn(100)
}
df = pd.DataFrame(data)
# 定义中间值(十字交叉点)
x_median = df['x'].median()
y_median = df['y'].median()
# 添加象限列
def get_quadrant(row):
if row['x'] < x_median and row['y'] >= y_median:
return 'Q1'
elif row['x'] >= x_median and row['y'] >= y_median:
return 'Q2'
elif row['x'] < x_median and row['y'] < y_median:
return 'Q3'
elif row['x'] >= x_median and row['y'] < y_median:
return 'Q4'
df['quadrant'] = df.apply(get_quadrant, axis=1)
# 设置颜色
colors = {
'Q1': 'lightgreen', # 左上方
'Q2': 'darkgreen', # 右上方
'Q3': 'darkred', # 左下方
'Q4': 'red' # 右下方
}
# 画布大小
plt.figure(figsize=(10, 10))
# 绘制散点图
for quadrant, color in colors.items():
subset = df[df['quadrant'] == quadrant]
plt.scatter(subset['x'], subset['y'], c=color, label=quadrant, alpha=0.6)
# 中间线
plt.axhline(y=y_median, color='k', linestyle='--', linewidth=1)
plt.axvline(x=x_median, color='k', linestyle='--', linewidth=1)
# 图例
plt.legend()
plt.title("四象限图")
plt.xlabel("X 轴")
plt.ylabel("Y 轴")
plt.grid(True)
plt.show()
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# 示例数据,包括年份和周数
np.random.seed(0)
dates = pd.date_range(start="2022-01-01", periods=100, freq='W')
data = {
'date': dates,
'x': np.random.randn(100),
'y': np.random.randn(100)
}
df = pd.DataFrame(data)
df['year'] = df['date'].dt.year
df['week'] = df['date'].dt.isocalendar().week
# 定义中间值(十字交叉点)
x_median = df['x'].median()
y_median = df['y'].median()
# 添加象限列
def get_quadrant(row):
if row['x'] < x_median and row['y'] >= y_median:
return 'Q1'
elif row['x'] >= x_median and row['y'] >= y_median:
return 'Q2'
elif row['x'] < x_median and row['y'] < y_median:
return 'Q3'
elif row['x'] >= x_median and row['y'] < y_median:
return 'Q4'
df['quadrant'] = df.apply(get_quadrant, axis=1)
# 设置颜色
colors = {
'Q1': 'lightgreen', # 左上方
'Q2': 'darkgreen', # 右上方
'Q3': 'darkred', # 左下方
'Q4': 'red' # 右下方
}
# 分割数据
last_year = df[df['year'] == df['year'].max() - 1]
this_year = df[df['year'] == df['year'].max()]
recent_12_weeks = this_year.sort_values(by='date').tail(12)
# 画布大小
plt.figure(figsize=(10, 10))
# 去年数据用灰色
plt.scatter(last_year['x'], last_year['y'], c='gray', alpha=0.6, label='Last Year')
# 今年数据按照象限颜色
for quadrant, color in colors.items():
subset = this_year[this_year['quadrant'] == quadrant]
plt.scatter(subset['x'], subset['y'], c=color, alpha=0.6, label=f'This Year {quadrant}')
# 最近12周数据用蓝色直线连接
plt.plot(recent_12_weeks['x'], recent_12_weeks['y'], c='blue', lw=2, label='Recent 12 Weeks')
# 中间线
plt.axhline(y=y_median, color='k', linestyle='--', linewidth=1)
plt.axvline(x=x_median, color='k', linestyle='--', linewidth=1)
# 图例
plt.legend()
plt.title("四象限图")
plt.xlabel("X 轴")
plt.ylabel("Y 轴")
plt.grid(True)
plt.show()