使用Matplotlib绘制游戏内货币学分析与玩家消费行为洞察及经济系统平衡性研究

引言:游戏内经济学的重要性
在现代游戏设计中,游戏内经济系统(In-game Economy)是维持玩家长期参与度和商业变现的核心支柱。一个设计良好的经济系统不仅能提升玩家体验,还能通过合理的货币循环实现可持续的商业回报。然而,设计和维护这样一个系统需要深入的数据分析和可视化支持。
Matplotlib作为Python中最基础且强大的数据可视化库,为游戏经济学家和数据分析师提供了理想的工具。通过Matplotlib,我们可以将复杂的玩家行为数据转化为直观的图表,从而发现潜在问题、识别消费模式并优化经济平衡性。
本文将通过一个完整的案例,展示如何使用Matplotlib进行游戏内货币学分析,涵盖数据准备、基础可视化、高级图表以及经济系统平衡性评估。
1. 数据准备与模拟
在进行实际分析之前,我们需要准备模拟数据。在真实的游戏场景中,这些数据通常来自服务器日志、数据库或分析平台。为了演示,我们将创建一个包含以下维度的模拟数据集:
玩家基础信息
:玩家ID、等级、注册时间
货币数据
:金币(软货币)、钻石(硬货币)的获取与消耗
交易记录
:购买时间、商品类型、价格、支付方式
行为数据
:在线时长、关卡进度、社交互动
1.1 创建模拟数据集
我们将使用Pandas和NumPy生成模拟数据,然后用Matplotlib进行可视化分析。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime, timedelta
import seaborn as sns # 用于辅助样式,但核心绘图仍用Matplotlib

# 设置中文字体(如果系统支持)
plt.rcParams[‘font.sans-serif’] = [‘SimHei’] # 用来正常显示中文标签
plt.rcParams[‘axes.unicode_minus’] = False # 用来正常显示负号

# 设置随机种子以保证结果可复现
np.random.seed(42)

# 生成模拟玩家数据
def generate_player_data(num_players=1000):
“””生成模拟玩家基础数据”””
player_ids = [f”P{i:05d}” for i in range(num_players)]
levels = np.random.randint(1, 50, num_players)
registration_dates = [
datetime(2024, 1, 1) + timedelta(days=np.random.randint(0, 365))
for _ in range(num_players)
]

# 玩家类型分类:免费玩家、小额付费、中额付费、大额付费
player_types = np.random.choice(
[‘Free’, ‘Minnow’, ‘Dolphin’, ‘Whale’],
size=num_players,
p=[0.6, 0.25, 0.12, 0.03]
)

# 基于类型生成消费金额
spending_map = {
‘Free’: 0,
‘Minnow’: np.random.uniform(5, 50, num_players),
‘Dolphin’: np.random.uniform(50, 200, num_players),
‘Whale’: np.random.uniform(200, 1000, num_players)
}

total_spending = np.array([
spending_map[ptype][i] if ptype != ‘Free’ else 0
for i, ptype in enumerate(player_types)
])

df_players = pd.DataFrame({
‘player_id’: player_ids,
‘level’: levels,
‘registration_date’: registration_dates,
‘player_type’: player_types,
‘total_spending’: total_spending
})

return df_players

# 生成交易记录
def generate_transaction_data(players, num_transactions=5000):
“””生成模拟交易数据”””
transactions = []

for _ in range(num_transactions):
# 随机选择玩家
player_idx = np.random.randint(0, len(players))
player = players.iloc[player_idx]

# 交易时间(在注册日期之后)
trans_date = player[‘registration_date’] + timedelta(
days=np.random.randint(0, 365),
hours=np.random.randint(0, 24),
minutes=np.random.randint(0, 60)
)

# 商品类型和价格
item_types = [‘Bundle’, ‘Currency’, ‘Skin’, ‘BattlePass’, ‘Energy’]
item_type = np.random.choice(item_types, p=[0.3, 0.25, 0.2, 0.15, 0.1])

# 价格范围
price_ranges = {
‘Bundle’: (5, 20),
‘Currency’: (2, 15),
‘Skin’: (10, 30),
‘BattlePass’: (10, 15),
‘Energy’: (1, 5)
}
price = np.random.uniform(*price_ranges[item_type])

# 支付方式
payment_method = np.random.choice([‘Credit Card’, ‘PayPal’, ‘Google Pay’, ‘Apple Pay’],
p=[0.4, 0.3, 0.2, 0.1])

transactions.append({
‘player_id’: player[‘player_id’],
‘transaction_date’: trans_date,
‘item_type’: item_type,
‘price’: price,
‘payment_method’: payment_method,
‘player_type’: player[‘player_type’]
})

return pd.DataFrame(transactions)

# 生成货币流动数据
def generate_currency_flow(players):
“””生成金币和钻石的获取与消耗数据”””
currency_data = []

for _, player in players.iterrows():
# 基于玩家类型和等级生成货币流动
base_activity = player[‘level’] * 10

if player[‘player_type’] == ‘Free’:
gold_earned = base_activity * np.random.uniform(0.8, 1.2)
gold_spent = gold_earned * np.random.uniform(0.6, 0.9)
diamond_earned = base_activity * 0.1
diamond_spent = 0
elif player[‘player_type’] == ‘Minnow’:
gold_earned = base_activity * np.random.uniform(1.0, 1.5)
gold_spent = gold_earned * np.random.uniform(0.7, 1.0)
diamond_earned = base_activity * 0.3
diamond_spent = diamond_0.2 * np.random.uniform(0.5, 0.8)
elif player[‘player_type’] == ‘Dolphin’:
gold_earned = base_activity * np.random.uniform(1.2, 2.0)
gold_spent = gold_earned * np.random.uniform(0.8, 1.1)
diamond_earned = base_activity * 0.8
diamond_spent = diamond_earned * np.random.uniform(0.6, 0.9)
else: # Whale
gold_earned = base_activity * np.random.uniform(1.5, 3.0)
gold_spent = gold_earned * np.random.uniform(0.9, 1.2)
diamond_earned = base_activity * 2.0
diamond_spent = diamond_earned * np.random.uniform(0.7, 1.0)

currency_data.append({
‘player_id’: player[‘player_id’],
‘gold_earned’: gold_earned,
‘gold_spent’: gold_spent,
‘diamond_earned’: diamond_earned,
‘diamond_spent’: diamond_spent,
‘player_type’: player[‘player_type’]
})

return pd.DataFrame(currency_data)

# 生成所有数据
print(“正在生成模拟数据…”)
df_players = generate_player_data(1000)
df_transactions = generate_transaction_data(df_players, 5000)
df_currency = generate_currency_flow(df_players)

print(f”生成 {len(df_players)} 名玩家数据”)
print(f”生成 {len(df_transactions)} 条交易记录”)
print(f”生成 {len(df_currency)} 条货币流动记录”)
2. 玩家消费行为分析
2.1 玩家分层分析(RFM模型简化版)
在游戏经济学中,玩家通常被分为不同层级:免费玩家(Free)、小额付费(Minnow)、中额付费(Dolphin)和大额付费(Whale)。理解各层级玩家的分布和贡献是经济分析的基础。
def plot_player_distribution():
“””绘制玩家层级分布”””
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))

# 1. 玩家数量分布
player_counts = df_players[‘player_type’].value_counts()
colors = [‘#E0E0E0’, ‘#4CAF50’, ‘#2196F3’, ‘#FF5722′] # Free, Minnow, Dolphin, Whale

wedges, texts, autotexts = ax1.pie(
player_counts.values,
labels=player_counts.index,
autopct=’%1.1f%%’,
startangle=90,
colors=colors,
explode=(0, 0.05, 0.1, 0.15)
)

for autotext in autotexts:
autotext.set_color(‘white’)
autotext.set_fontweight(‘bold’)

ax1.set_title(‘玩家层级分布’, fontsize=14, fontweight=’bold’)

# 2. 收入贡献分布
revenue_by_type = df_players.groupby(‘player_type’)[‘total_spending’].sum()
revenue_pct = revenue_by_type / revenue_by_type.sum() * 100

bars = ax2.bar(revenue_pct.index, revenue_pct.values, color=colors)
ax2.set_title(‘收入贡献分布’, fontsize=14, fontweight=’bold’)
ax2.set_ylabel(‘收入占比 (%)’)
ax2.set_ylim(0, 100)

# 在柱子上添加数值标签
for bar, pct in zip(bars, revenue_pct.values):
height = bar.get_height()
ax2.text(bar.get_x() + bar.get_width()/2., height + 1,
f'{pct:.1f}%’, ha=’center’, va=’bottom’, fontweight=’bold’)

plt.tight_layout()
plt.show()

# 执行绘图
plot_player_distribution()
分析说明
:
免费玩家(60%)
:数量最多但贡献为0,需要通过广告或社交裂变实现价值
小额付费(25%)
:数量第二,贡献约15-20%收入,是转化重点
中额付费(12%)
:数量少但贡献显著(约30-40%)
大额付费(3%)
:鲸鱼用户,贡献超过50%收入,需要重点维护
2.2 消费时间模式分析
分析玩家在一天中的消费时间分布,有助于优化促销活动时间安排。
def plot_consumption_pattern():
“””绘制消费时间模式”””
fig, ax = plt.subplots(figsize=(14, 7))

# 提取交易时间的小时
df_transactions[‘hour’] = df_transactions[‘transaction_date’].dt.hour

# 按小时和玩家类型统计交易次数
hourly_pattern = df_transactions.groupby([‘hour’, ‘player_type’]).size().unstack(fill_value=0)

# 绘制堆叠面积图
colors = [‘#E0E0E0’, ‘#4CAF50’, ‘#2196F3’, ‘#FF5722′]
hourly_pattern.plot(kind=’area’, stacked=True, ax=ax, color=colors, alpha=0.8)

ax.set_title(’24小时消费时间模式分析’, fontsize=16, fontweight=’bold’)
ax.set_xlabel(‘小时 (24小时制)’, fontsize=12)
ax.set_ylabel(‘交易次数’, fontsize=12)
ax.legend(title=’玩家类型’, loc=’upper right’)
ax.grid(True, alpha=0.3)

# 标记高峰时段
peak_hour = hourly_pattern.sum(axis=1).idxmax()
ax.axvline(x=peak_hour, color=’red’, linestyle=’–‘, alpha=0.7, label=f’峰值小时: {peak_hour}:00’)

plt.tight_layout()
plt.show()

plot_consumption_pattern()
分析洞察
:
高峰时段
:通常在晚上19:00-22:00,这是玩家最活跃的时间
鲸鱼用户
:可能在凌晨或工作时段也有消费,显示其高活跃度
运营建议
:在高峰时段前1小时(18:00)推送限时折扣,转化率最高
2.3 商品类型偏好分析
def plot_item_preference():
“””绘制商品类型偏好”””
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))

# 1. 各玩家类型购买的商品类型分布
item_by_player = df_transactions.groupby([‘player_type’, ‘item_type’]).size().unstack(fill_value=0)
item_by_player_pct = item_by_player.div(item_by_player.sum(axis=1), axis=0) * 100

# 绘制热力图
im = ax1.imshow(item_by_player_pct.values, cmap=’YlOrRd’, aspect=’auto’)
ax1.set_xticks(range(len(item_by_player_pct.columns)))
ax1.set_xticklabels(item_by_player_pct.columns, rotation=45)
ax1.set_yticks(range(len(item_by_player_pct.index)))
ax1.set_yticklabels(item_by_player_pct.index)
ax1.set_title(‘商品类型偏好热力图 (%)’, fontsize=14, fontweight=’bold’)

# 添加数值标签
for i in range(len(item_by_player_pct.index)):
for j in range(len(item_by_player_pct.columns)):
text = ax1.text(j, i, f'{item_by_player_pct.iloc[i, j]:.1f}’,
ha=”center”, va=”center”, color=”black”, fontsize=9)

# 2. 平均交易金额对比
avg_price_by_item = df_transactions.groupby(‘item_type’)[‘price’].mean().sort_values(ascending=False)
bars = ax2.bar(avg_price_by_item.index, avg_price_by_item.values,
color=[‘#FF5722’, ‘#2196F3’, ‘#4CAF50’, ‘#9C27B0’, ‘#FF9800’])

ax2.set_title(‘各商品类型平均交易金额’, fontsize=14, fontweight=’bold’)
ax2.set_ylabel(‘平均价格 ($)’)
ax2.tick_params(axis=’x’, rotation=45)

# 添加数值标签
for bar, value in zip(bars, avg_price_by_item.values):
ax2.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 0.1,
f’${value:.2f}’, ha=’center’, va=’bottom’, fontweight=’bold’)

plt.tight_layout()
plt.show()

plot_item_preference()
分析洞察
:
Bundle(捆绑包)
:平均价格最高,适合大额付费用户
BattlePass
:性价比高,是提升留存和转化的核心商品
Energy(体力)
:单价低但购买频次高,适合小额付费用户
Skin(皮肤)
:中等价格,外观党最爱,适合中额付费用户
3. 货币学分析
3.1 货币获取与消耗平衡性
经济系统平衡性的核心是确保货币的获取与消耗保持动态平衡,避免通货膨胀或通货紧缩。
def plot_currency_balance():
“””绘制货币平衡性分析”””
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
axes = axes.flatten()

# 1. 金币获取与消耗对比(按玩家类型)
gold_balance = df_currency.groupby(‘player_type’).agg({
‘gold_earned’: ‘sum’,
‘gold_spent’: ‘sum’
})

x = np.arange(len(gold_balance.index))
width = 0.35

axes[0].bar(x – width/2, gold_balance[‘gold_earned’], width, label=’金币获取’, color=’#4CAF50′, alpha=0.8)
axes[0].bar(x + width/2, gold_balance[‘gold_spent’], width, label=’金币消耗’, color=’#FF5722′, alpha=0.8)

axes[0].set_title(‘金币获取 vs 消耗 (按玩家类型)’, fontsize=14, fontweight=’bold’)
axes[0].set_ylabel(‘数量’)
axes[0].set_xticks(x)
axes[0].set_xticklabels(gold_balance.index)
axes[0].legend()
axes[0].grid(True, alpha=0.3, axis=’y’)

# 添加平衡性指标
balance_ratio = gold_balance[‘gold_spent’] / gold_balance[‘gold_earned’]
for i, ratio in enumerate(balance_ratio):
axes[0].text(i, gold_balance[‘gold_earned’].iloc[i] * 1.05,
f’消耗率: {ratio:.2f}’, ha=’center’, fontsize=9, color=’blue’)

# 2. 钻石获取与消耗对比
diamond_balance = df_currency.groupby(‘player_type’).agg({
‘diamond_earned’: ‘sum’,
‘diamond_spent’: ‘sum’
})

axes[1].bar(x – width/2, diamond_balance[‘diamond_earned’], width, label=’钻石获取’, color=’#2196F3′, alpha=0.8)
axes[1].bar(x + width/2, diamond_balance[‘diamond_spent’], width, label=’钻石消耗’, color=’#FF5722′, alpha=0.8)

axes[1].set_title(‘钻石获取 vs 消耗 (按玩家类型)’, fontsize=14, fontweight=’bold’)
axes[1].set_ylabel(‘数量’)
axes[1].set_xticks(x)
axes[1].set_xticklabels(diamond_balance.index)
axes[1].legend()
axes[1].grid(True, alpha=0.3, axis=’y’)

# 3. 货币流通速度(每日)
# 模拟每日活跃玩家的货币流动
daily_gold_flow = df_currency[‘gold_earned’].sum() / 30 # 假设30天
daily_diamond_flow = df_currency[‘diamond_earned’].sum() / 30

flow_data = [daily_gold_flow, daily_diamond_flow]
flow_labels = [‘金币’, ‘钻石’]

bars = axes[2].bar(flow_labels, flow_data, color=[‘#4CAF50’, ‘#2196F3’], alpha=0.8)
axes[2].set_title(‘日均货币流通量’, fontsize=14, fontweight=’bold’)
axes[2].set_ylabel(‘数量’)

for bar, value in zip(bars, flow_data):
axes[2].text(bar.get_x() + bar.get_width()/2., bar.get_height() + 10,
f'{value:.0f}’, ha=’center’, va=’bottom’, fontweight=’bold’)

# 4. 货币储备分析(获取-消耗)
net_gold = df_currency[‘gold_earned’].sum() – df_currency[‘gold_spent’].sum()
net_diamond = df_currency[‘diamond_earned’].sum() – df_currency[‘diamond_spent’].sum()

net_data = [net_gold, net_diamond]
colors = [‘#4CAF50’ if x >= 0 else ‘#FF5722′ for x in net_data]

bars = axes[3].bar(flow_labels, net_data, color=colors, alpha=0.8)
axes[3].axhline(y=0, color=’black’, linestyle=’-‘, linewidth=0.8)
axes[3].set_title(‘净货币储备 (获取-消耗)’, fontsize=14, fontweight=’bold’)
axes[3].set_ylabel(‘净数量’)

for bar, value in zip(bars, net_data):
axes[3].text(bar.get_x() + bar.get_width()/2.,
value + (10 if value >= 0 else -20),
f'{value:.0f}’, ha=’center’, va=’bottom’ if value >= 0 else ‘top’,
fontweight=’bold’, color=’black’)

plt.tight_layout()
plt.show()

plot_currency_balance()
平衡性评估
:
金币
:如果消耗率 < 0.8,说明金币获取过多,可能导致通货膨胀 钻石 :如果消耗率 > 1.0,说明钻石获取不足,可能抑制消费
理想状态
:消耗率在0.85-0.95之间,保持轻微通胀以激励玩家获取更多货币
3.2 通货膨胀率计算与可视化
def plot_inflation_analysis():
“””绘制通货膨胀分析”””
fig, ax = plt.subplots(figsize=(14, 8))

# 模拟时间序列数据(30天)
dates = pd.date_range(start=’2024-01-01′, periods=30, freq=’D’)

# 模拟基础物价指数(100为基准)
base_price_index = 100

# 根据货币净增发计算通胀率
# 假设每天货币净增发导致物价上涨
daily_net_gold = df_currency[‘gold_earned’].sum() / 30 – df_currency[‘gold_spent’].sum() / 30
daily_net_diamond = df_currency[‘diamond_earned’].sum() / 30 – df_currency[‘diamond_spent’].sum() / 30

# 通胀率计算(简化模型)
inflation_rate_gold = (daily_net_gold / (df_currency[‘gold_earned’].sum() / 30)) * 100
inflation_rate_diamond = (daily_net_diamond / (df_currency[‘diamond_earned’].sum() / 30)) * 100

# 生成时间序列
gold_inflation = base_price_index * (1 + inflation_rate_gold/100)**np.arange(30)
diamond_inflation = base_price_index * (1 + inflation_rate_diamond/100)**np.arange(30)

# 绘制
ax.plot(dates, gold_inflation, label=’金币通胀指数’, color=’#4CAF50′, linewidth=2, marker=’o’, markersize=4)
ax.plot(dates, diamond_inflation, label=’钻石通胀指数’, color=’#2196F3′, linewidth=2, marker=’s’, markersize=4)
ax.axhline(y=base_price_index, color=’gray’, linestyle=’–‘, alpha=0.7, label=’基准线 (100)’)

ax.set_title(’30天货币通胀趋势分析’, fontsize=16, fontweight=’bold’)
ax.set_xlabel(‘日期’, fontsize=12)
ax.set_ylabel(‘物价指数’, fontsize=12)
ax.legend()
ax.grid(True, alpha=0.3)

# 格式化x轴日期
ax.xaxis.set_major_formatter(mdates.DateFormatter(‘%m-%d’))
plt.xticks(rotation=45)

# 添加通胀率标签
ax.text(0.02, 0.95, f’日均金币通胀率: {inflation_rate_gold:.3f}%’,
transform=ax.transAxes, fontsize=10,
bbox=dict(boxstyle=”round,pad=0.3″, facecolor=”#4CAF50″, alpha=0.2))
ax.text(0.02, 0.88, f’日均钻石通胀率: {inflation_rate_diamond:.3f}%’,
transform=ax.transAxes, fontsize=10,
bbox=dict(boxstyle=”round,pad=0.3″, facecolor=”#2196F3″, alpha=0.2))

plt.tight_layout()
plt.show()

plot_inflation_analysis()
通胀控制策略
:
高通胀(>1%)
:增加消耗途径,如限时商店、强化失败消耗、排行榜税收
低通胀(<0.1%) :增加获取途径,如日常任务奖励、登录奖励 负通胀 :立即增加货币投放,避免经济停滞 4. 经济系统平衡性研究 4.1 玩家生命周期价值(LTV)分析 def plot_ltv_analysis(): """绘制LTV分析""" fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6)) # 1. 各玩家类型的平均LTV ltv_by_type = df_players.groupby('player_type')['total_spending'].agg(['mean', 'median', 'std']) # 绘制带误差线的柱状图 colors = ['#E0E0E0', '#4CAF50', '#2196F3', '#FF5722'] bars = ax1.bar(ltv_by_type.index, ltv_by_type['mean'], yerr=ltv_by_type['std'], capsize=5, color=colors, alpha=0.8, error_kw={'elinewidth': 2, 'ecolor': 'black', 'capthick': 2}) ax1.set_title('各玩家类型平均LTV (生命周期价值)', fontsize=14, fontweight='bold') ax1.set_ylabel('平均消费金额 ($)') ax1.grid(True, alpha=0.3, axis='y') # 添加数值标签 for bar, value in zip(bars, ltv_by_type['mean'].values): ax1.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 1, f'${value:.1f}', ha='center', va='bottom', fontweight='bold') # 2. LTV分布直方图(按玩家类型) for i, ptype in enumerate(df_players['player_type'].unique()): data = df_players[df_players['player_type'] == ptype]['total_spending'] if len(data) > 0:
ax2.hist(data, bins=20, alpha=0.6, label=ptype, color=colors[i], density=True)

ax2.set_title(‘LTV分布密度图’, fontsize=14, fontweight=’bold’)
ax2.set_xlabel(‘消费金额 ($)’)
ax2.set_ylabel(‘密度’)
ax2.legend()
ax2.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

plot_ltv_analysis()
4.2 经济系统健康度仪表板
def create_economic_dashboard():
“””创建经济系统健康度仪表板”””
fig = plt.figure(figsize=(18, 12))
gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3)

# 1. 收入结构饼图
ax1 = fig.add_subplot(gs[0, 0])
revenue_by_type = df_players.groupby(‘player_type’)[‘total_spending’].sum()
colors = [‘#E0E0E0’, ‘#4CAF50’, ‘#2196F3’, ‘#FF5722′]
wedges, texts, autotexts = ax1.pie(revenue_by_type.values, labels=revenue_by_type.index,
autopct=’%1.1f%%’, colors=colors, startangle=90)
ax1.set_title(‘收入结构’, fontweight=’bold’)

# 2. 货币平衡性
ax2 = fig.add_subplot(gs[0, 1])
gold_balance = df_currency[‘gold_earned’].sum() – df_currency[‘gold_spent’].sum()
diamond_balance = df_currency[‘diamond_earned’].sum() – df_currency[‘diamond_spent’].sum()

balance_data = [gold_balance, diamond_balance]
balance_labels = [‘金币’, ‘钻石’]
colors_balance = [‘#4CAF50’ if x >= 0 else ‘#FF5722′ for x in balance_data]

bars = ax2.bar(balance_labels, balance_data, color=colors_balance, alpha=0.8)
ax2.axhline(y=0, color=’black’, linestyle=’-‘, linewidth=0.8)
ax2.set_title(‘货币净储备’, fontweight=’bold’)
ax2.set_ylabel(‘净数量’)

for bar, value in zip(bars, balance_data):
ax2.text(bar.get_x() + bar.get_width()/2.,
value + (50 if value >= 0 else -100),
f'{value:.0f}’, ha=’center’, va=’bottom’ if value >= 0 else ‘top’,
fontweight=’bold’)

# 3. 消费转化率
ax3 = fig.add_subplot(gs[0, 2])
paying_players = len(df_players[df_players[‘total_spending’] > 0])
total_players = len(df_players)
conversion_rate = paying_players / total_players * 100

ax3.pie([conversion_rate, 100-conversion_rate],
labels=[‘付费玩家’, ‘免费玩家’],
autopct=’%1.1f%%’,
colors=[‘#FF5722’, ‘#E0E0E0′],
startangle=90)
ax3.set_title(f’付费转化率\n({conversion_rate:.1f}%)’, fontweight=’bold’)

# 4. 商品销售分布
ax4 = fig.add_subplot(gs[1, :2])
item_sales = df_transactions[‘item_type’].value_counts()
bars = ax4.barh(item_sales.index, item_sales.values, color=’#2196F3′, alpha=0.8)
ax4.set_title(‘商品销售量分布’, fontweight=’bold’)
ax4.set_xlabel(‘销售数量’)

for bar, value in zip(bars, item_sales.values):
ax4.text(bar.get_width() + 10, bar.get_y() + bar.get_height()/2.,
f'{value}’, va=’center’, fontweight=’bold’)

# 5. 收入时间趋势
ax5 = fig.add_subplot(gs[1, 2])
daily_revenue = df_transactions.groupby(df_transactions[‘transaction_date’].dt.date)[‘price’].sum()
ax5.plot(daily_revenue.index, daily_revenue.values, color=’#FF5722′, linewidth=2, marker=’o’, markersize=3)
ax5.set_title(‘日收入趋势’, fontweight=’bold’)
ax5.set_ylabel(‘收入 ($)’)
ax5.tick_params(axis=’x’, rotation=45)
ax5.grid(True, alpha=0.3)

# 6. 玩家活跃度与消费关系
ax6 = fig.add_subplot(gs[2, :])
# 模拟活跃度数据(基于等级和注册时间)
df_players[‘days_since_reg’] = (datetime.now() – df_players[‘registration_date’]).dt.days
df_players[‘activity_score’] = df_players[‘level’] * np.log1p(df_players[‘days_since_reg’])

# 绘制散点图
scatter = ax6.scatter(df_players[‘activity_score’], df_players[‘total_spending’],
c=df_players[‘player_type’].astype(‘category’).cat.codes,
cmap=’viridis’, alpha=0.6, s=50)

ax6.set_title(‘活跃度 vs 消费金额 (颜色代表玩家类型)’, fontweight=’bold’)
ax6.set_xlabel(‘活跃度评分’)
ax6.set_ylabel(‘消费金额 ($)’)
ax6.grid(True, alpha=0.3)

# 添加颜色条
cbar = plt.colorbar(scatter, ax=ax6)
cbar.set_ticks([0, 1, 2, 3])
cbar.set_ticklabels([‘Free’, ‘Minnow’, ‘Dolphin’, ‘Whale’])

plt.suptitle(‘游戏经济系统健康度仪表板’, fontsize=20, fontweight=’bold’, y=0.995)
plt.show()

create_economic_dashboard()
5. 高级分析:预测与优化建议
5.1 玩家流失预警模型
def plot_churn_prediction():
“””绘制流失预警分析”””
fig, ax = plt.subplots(figsize=(14, 8))

# 基于消费频率和最近消费时间预测流失风险
# 模拟:最近30天无消费且活跃度低的玩家视为高流失风险

# 计算每个玩家的最近消费时间
latest_transactions = df_transactions.groupby(‘player_id’)[‘transaction_date’].max()
df_players[‘last_transaction’] = df_players[‘player_id’].map(latest_transactions)
df_players[‘days_since_last_purchase’] = (datetime.now() – df_players[‘last_transaction’]).dt.days.fillna(365)

# 计算消费频率
purchase_count = df_transactions.groupby(‘player_id’).size()
df_players[‘purchase_frequency’] = df_players[‘player_id’].map(purchase_count).fillna(0)

# 定义流失风险
def get_churn_risk(row):
if row[‘player_type’] == ‘Free’:
return ‘Low’ # 免费玩家不计算流失
if row[‘days_since_last_purchase’] > 30 and row[‘purchase_frequency’] < 2: return 'High' elif row['days_since_last_purchase'] > 14:
return ‘Medium’
else:
return ‘Low’

df_players[‘churn_risk’] = df_players.apply(get_churn_risk, axis=1)

# 绘制风险分布
risk_counts = df_players[df_players[‘player_type’] != ‘Free’][‘churn_risk’].value_counts()
colors = {‘Low’: ‘#4CAF50’, ‘Medium’: ‘#FF9800’, ‘High’: ‘#FF5722’}

bars = ax.bar(risk_counts.index, risk_counts.values,
color=[colors[r] for r in risk_counts.index], alpha=0.8)

ax.set_title(‘付费玩家流失风险分布’, fontsize=16, fontweight=’bold’)
ax.set_ylabel(‘玩家数量’)
ax.set_xlabel(‘风险等级’)

for bar, value in zip(bars, risk_counts.values):
ax.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 1,
f'{value}\n({value/risk_counts.sum()*100:.1f}%)’,
ha=’center’, va=’bottom’, fontweight=’bold’)

# 添加行动建议
high_risk_pct = risk_counts.get(‘High’, 0) / risk_counts.sum() * 100
if high_risk_pct > 20:
action = “立即启动召回活动!”
color = ‘#FF5722’
elif high_risk_pct > 10:
action = “准备召回策略”
color = ‘#FF9800’
else:
action = “维持现状”
color = ‘#4CAF50′

ax.text(0.02, 0.95, f’行动建议: {action}\n高风险玩家占比: {high_risk_pct:.1f}%’,
transform=ax.transAxes, fontsize=11, fontweight=’bold’,
bbox=dict(boxstyle=”round,pad=0.5″, facecolor=color, alpha=0.3))

plt.tight_layout()
plt.show()

plot_churn_prediction()
5.2 经济系统优化建议生成器
def generate_optimization_report():
“””生成经济系统优化报告”””
print(“=”*60)
print(“游戏经济系统优化报告”)
print(“=”*60)

# 1. 收入分析
total_revenue = df_players[‘total_spending’].sum()
avg_revenue_per_paying = df_players[df_players[‘total_spending’] > 0][‘total_spending’].mean()
conversion_rate = len(df_players[df_players[‘total_spending’] > 0]) / len(df_players) * 100

print(f”\n📊 收入概览:”)
print(f” 总收入: ${total_revenue:,.2f}”)
print(f” 付费玩家平均收入: ${avg_revenue_per_paying:.2f}”)
print(f” 付费转化率: {conversion_rate:.1f}%”)

# 2. 货币平衡性
gold_balance = df_currency[‘gold_earned’].sum() – df_currency[‘gold_spent’].sum()
diamond_balance = df_currency[‘diamond_earned’].sum() – df_currency[‘diamond_spent’].sum()

print(f”\n💰 货币平衡性:”)
print(f” 金币净储备: {gold_balance:.0f} (消耗率: {df_currency[‘gold_spent’].sum()/df_currency[‘gold_earned’].sum():.2f})”)
print(f” 钻石净储备: {diamond_balance:.0f} (消耗率: {df_currency[‘diamond_spent’].sum()/df_currency[‘diamond_earned’].sum():.2f})”)

# 3. 商品表现
item_performance = df_transactions.groupby(‘item_type’).agg({
‘price’: [‘count’, ‘sum’]
}).round(2)
item_performance.columns = [‘销售次数’, ‘总收入’]

print(f”\n📦 商品表现:”)
print(item_performance.to_string())

# 4. 优化建议
print(f”\n💡 优化建议:”)

# 检查通胀
gold_inflation = gold_balance / df_currency[‘gold_earned’].sum()
if gold_inflation > 0.2:
print(” ⚠️ 金币通胀风险高: 建议增加金币消耗途径(如装备强化、排行榜税收)”)
elif gold_inflation < 0.05: print(" ✅ 金币流通健康") # 检查转化率 if conversion_rate < 5: print(" ⚠️ 付费转化率低: 建议优化新手引导,增加首充优惠") elif conversion_rate > 15:
print(” ✅ 付费转化率优秀”)

# 检查鲸鱼用户依赖度
whale_revenue = df_players[df_players[‘player_type’] == ‘Whale’][‘total_spending’].sum()
whale_pct = whale_revenue / total_revenue * 100
if whale_pct > 60:
print(f” ⚠️ 收入过度依赖鲸鱼用户 ({whale_pct:.1f}%): 建议加强中额付费用户转化”)
else:
print(” ✅ 收入结构健康”)

# 商品建议
bundle_sales = item_performance.loc[‘Bundle’, ‘销售次数’]
if bundle_sales < item_performance['销售次数'].sum() * 0.2: print(" 💡 捆绑包销售占比低: 建议优化捆绑包内容或定价策略") print("\n" + "="*60) generate_optimization_report() 6. 实际应用案例与最佳实践 6.1 案例:某RPG游戏的经济系统崩溃与修复 问题识别 : 通过Matplotlib绘制的货币平衡图发现,金币在30天内净增发了500万,而消耗仅200万,导致物价指数上涨300%。 修复措施 : 紧急措施 :立即上线限时商店,消耗过剩金币 中期调整 :增加装备强化失败消耗机制 长期优化 :引入金币回收系统(如排行榜税收) 效果验证 : 修复后,通过Matplotlib绘制的通胀曲线显示,通胀率从每日2%降至0.3%,经济系统恢复健康。 6.2 最佳实践总结 数据驱动决策 :所有经济调整必须基于数据可视化分析 A/B测试 :新经济功能上线前,必须进行小范围A/B测试 实时监控 :建立实时仪表板,监控关键指标(通胀率、转化率、ARPU) 玩家反馈 :结合定量数据与定性反馈,全面评估经济系统 7. 总结 通过Matplotlib的强大可视化能力,我们可以将复杂的游戏经济数据转化为直观的洞察。从玩家分层到货币平衡,从消费模式到流失预警,每一个分析维度都能为游戏运营提供决策支持。 关键要点 : 玩家分层 :识别并重点维护高价值用户 货币平衡 :保持获取与消耗的动态平衡,避免通胀或通缩 商品优化 :基于数据调整商品结构和定价策略 预测分析 :提前识别风险,主动干预 游戏经济系统是一个动态演化的生态系统,需要持续的数据监控和优化。Matplotlib作为可视化工具,是连接数据与决策的桥梁,帮助游戏开发者构建健康、可持续的虚拟经济。 附录:完整代码整合 # 完整代码整合(可直接运行) import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime, timedelta # 设置中文字体 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 数据生成函数(见上文) # ... [此处省略数据生成函数,实际使用时请包含] # 所有绘图函数(见上文) # ... [此处省略绘图函数,实际使用时请包含] # 主程序 if __name__ == "__main__": print("开始游戏经济系统分析...") # 生成数据 df_players = generate_player_data(1000) df_transactions = generate_transaction_data(df_players, 5000) df_currency = generate_currency_flow(df_players) # 执行所有分析 plot_player_distribution() plot_consumption_pattern() plot_item_preference() plot_currency_balance() plot_inflation_analysis() plot_ltv_analysis() create_economic_dashboard() plot_churn_prediction() generate_optimization_report() print("\n分析完成!所有图表已生成。") 通过这个完整的分析框架,你可以根据实际游戏数据快速生成专业的经济分析报告,为游戏运营提供有力支持。 # 使用Matplotlib绘制游戏内货币学分析与玩家消费行为洞察及经济系统平衡性研究 引言:游戏内经济学的重要性 在现代游戏设计中,游戏内经济系统(In-game Economy)是维持玩家长期参与度和商业变现的核心支柱。一个设计良好的经济系统不仅能提升玩家体验,还能通过合理的货币循环实现可持续的商业回报。然而,设计和维护这样一个系统需要深入的数据分析和可视化支持。 Matplotlib作为Python中最基础且强大的数据可视化库,为游戏经济学家和数据分析师提供了理想的工具。通过Matplotlib,我们可以将复杂的玩家行为数据转化为直观的图表,从而发现潜在问题、识别消费模式并优化经济平衡性。 本文将通过一个完整的案例,展示如何使用Matplotlib进行游戏内货币学分析,涵盖数据准备、基础可视化、高级图表以及经济系统平衡性评估。 1. 数据准备与模拟 在进行实际分析之前,我们需要准备模拟数据。在真实的游戏场景中,这些数据通常来自服务器日志、数据库或分析平台。为了演示,我们将创建一个包含以下维度的模拟数据集: 玩家基础信息 :玩家ID、等级、注册时间 货币数据 :金币(软货币)、钻石(硬货币)的获取与消耗 交易记录 :购买时间、商品类型、价格、支付方式 行为数据 :在线时长、关卡进度、社交互动 1.1 创建模拟数据集 我们将使用Pandas和NumPy生成模拟数据,然后用Matplotlib进行可视化分析。 import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime, timedelta import seaborn as sns # 用于辅助样式,但核心绘图仍用Matplotlib # 设置中文字体(如果系统支持) plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 # 设置随机种子以保证结果可复现 np.random.seed(42) # 生成模拟玩家数据 def generate_player_data(num_players=1000): """生成模拟玩家基础数据""" player_ids = [f"P{i:05d}" for i in range(num_players)] levels = np.random.randint(1, 50, num_players) registration_dates = [ datetime(2024, 1, 1) + timedelta(days=np.random.randint(0, 365)) for _ in range(num_players) ] # 玩家类型分类:免费玩家、小额付费、中额付费、大额付费 player_types = np.random.choice( ['Free', 'Minnow', 'Dolphin', 'Whale'], size=num_players, p=[0.6, 0.25, 0.12, 0.03] ) # 基于类型生成消费金额 spending_map = { 'Free': 0, 'Minnow': np.random.uniform(5, 50, num_players), 'Dolphin': np.random.uniform(50, 200, num_players), 'Whale': np.random.uniform(200, 1000, num_players) } total_spending = np.array([ spending_map[ptype][i] if ptype != 'Free' else 0 for i, ptype in enumerate(player_types) ]) df_players = pd.DataFrame({ 'player_id': player_ids, 'level': levels, 'registration_date': registration_dates, 'player_type': player_types, 'total_spending': total_spending }) return df_players # 生成交易记录 def generate_transaction_data(players, num_transactions=5000): """生成模拟交易数据""" transactions = [] for _ in range(num_transactions): # 随机选择玩家 player_idx = np.random.randint(0, len(players)) player = players.iloc[player_idx] # 交易时间(在注册日期之后) trans_date = player['registration_date'] + timedelta( days=np.random.randint(0, 365), hours=np.random.randint(0, 24), minutes=np.random.randint(0, 60) ) # 商品类型和价格 item_types = ['Bundle', 'Currency', 'Skin', 'BattlePass', 'Energy'] item_type = np.random.choice(item_types, p=[0.3, 0.25, 0.2, 0.15, 0.1]) # 价格范围 price_ranges = { 'Bundle': (5, 20), 'Currency': (2, 15), 'Skin': (10, 30), 'BattlePass': (10, 15), 'Energy': (1, 5) } price = np.random.uniform(*price_ranges[item_type]) # 支付方式 payment_method = np.random.choice(['Credit Card', 'PayPal', 'Google Pay', 'Apple Pay'], p=[0.4, 0.3, 0.2, 0.1]) transactions.append({ 'player_id': player['player_id'], 'transaction_date': trans_date, 'item_type': item_type, 'price': price, 'payment_method': payment_method, 'player_type': player['player_type'] }) return pd.DataFrame(transactions) # 生成货币流动数据 def generate_currency_flow(players): """生成金币和钻石的获取与消耗数据""" currency_data = [] for _, player in players.iterrows(): # 基于玩家类型和等级生成货币流动 base_activity = player['level'] * 10 if player['player_type'] == 'Free': gold_earned = base_activity * np.random.uniform(0.8, 1.2) gold_spent = gold_earned * np.random.uniform(0.6, 0.9) diamond_earned = base_activity * 0.1 diamond_spent = 0 elif player['player_type'] == 'Minnow': gold_earned = base_activity * np.random.uniform(1.0, 1.5) gold_spent = gold_earned * np.random.uniform(0.7, 1.0) diamond_earned = base_activity * 0.3 diamond_spent = diamond_earned * np.random.uniform(0.5, 0.8) elif player['player_type'] == 'Dolphin': gold_earned = base_activity * np.random.uniform(1.2, 2.0) gold_spent = gold_earned * np.random.uniform(0.8, 1.1) diamond_earned = base_activity * 0.8 diamond_spent = diamond_earned * np.random.uniform(0.6, 0.9) else: # Whale gold_earned = base_activity * np.random.uniform(1.5, 3.0) gold_spent = gold_earned * np.random.uniform(0.9, 1.2) diamond_earned = base_activity * 2.0 diamond_spent = diamond_earned * np.random.uniform(0.7, 1.0) currency_data.append({ 'player_id': player['player_id'], 'gold_earned': gold_earned, 'gold_spent': gold_spent, 'diamond_earned': diamond_earned, 'diamond_spent': diamond_spent, 'player_type': player['player_type'] }) return pd.DataFrame(currency_data) # 生成所有数据 print("正在生成模拟数据...") df_players = generate_player_data(1000) df_transactions = generate_transaction_data(df_players, 5000) df_currency = generate_currency_flow(df_players) print(f"生成 {len(df_players)} 名玩家数据") print(f"生成 {len(df_transactions)} 条交易记录") print(f"生成 {len(df_currency)} 条货币流动记录") 2. 玩家消费行为分析 2.1 玩家分层分析(RFM模型简化版) 在游戏经济学中,玩家通常被分为不同层级:免费玩家(Free)、小额付费(Minnow)、中额付费(Dolphin)和大额付费(Whale)。理解各层级玩家的分布和贡献是经济分析的基础。 def plot_player_distribution(): """绘制玩家层级分布""" fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6)) # 1. 玩家数量分布 player_counts = df_players['player_type'].value_counts() colors = ['#E0E0E0', '#4CAF50', '#2196F3', '#FF5722'] # Free, Minnow, Dolphin, Whale wedges, texts, autotexts = ax1.pie( player_counts.values, labels=player_counts.index, autopct='%1.1f%%', startangle=90, colors=colors, explode=(0, 0.05, 0.1, 0.15) ) for autotext in autotexts: autotext.set_color('white') autotext.set_fontweight('bold') ax1.set_title('玩家层级分布', fontsize=14, fontweight='bold') # 2. 收入贡献分布 revenue_by_type = df_players.groupby('player_type')['total_spending'].sum() revenue_pct = revenue_by_type / revenue_by_type.sum() * 100 bars = ax2.bar(revenue_pct.index, revenue_pct.values, color=colors) ax2.set_title('收入贡献分布', fontsize=14, fontweight='bold') ax2.set_ylabel('收入占比 (%)') ax2.set_ylim(0, 100) # 在柱子上添加数值标签 for bar, pct in zip(bars, revenue_pct.values): height = bar.get_height() ax2.text(bar.get_x() + bar.get_width()/2., height + 1, f'{pct:.1f}%', ha='center', va='bottom', fontweight='bold') plt.tight_layout() plt.show() # 执行绘图 plot_player_distribution() 分析说明 : 免费玩家(60%) :数量最多但贡献为0,需要通过广告或社交裂变实现价值 小额付费(25%) :数量第二,贡献约15-20%收入,是转化重点 中额付费(12%) :数量少但贡献显著(约30-40%) 大额付费(3%) :鲸鱼用户,贡献超过50%收入,需要重点维护 2.2 消费时间模式分析 分析玩家在一天中的消费时间分布,有助于优化促销活动时间安排。 def plot_consumption_pattern(): """绘制消费时间模式""" fig, ax = plt.subplots(figsize=(14, 7)) # 提取交易时间的小时 df_transactions['hour'] = df_transactions['transaction_date'].dt.hour # 按小时和玩家类型统计交易次数 hourly_pattern = df_transactions.groupby(['hour', 'player_type']).size().unstack(fill_value=0) # 绘制堆叠面积图 colors = ['#E0E0E0', '#4CAF50', '#2196F3', '#FF5722'] hourly_pattern.plot(kind='area', stacked=True, ax=ax, color=colors, alpha=0.8) ax.set_title('24小时消费时间模式分析', fontsize=16, fontweight='bold') ax.set_xlabel('小时 (24小时制)', fontsize=12) ax.set_ylabel('交易次数', fontsize=12) ax.legend(title='玩家类型', loc='upper right') ax.grid(True, alpha=0.3) # 标记高峰时段 peak_hour = hourly_pattern.sum(axis=1).idxmax() ax.axvline(x=peak_hour, color='red', linestyle='--', alpha=0.7, label=f'峰值小时: {peak_hour}:00') plt.tight_layout() plt.show() plot_consumption_pattern() 分析洞察 : 高峰时段 :通常在晚上19:00-22:00,这是玩家最活跃的时间 鲸鱼用户 :可能在凌晨或工作时段也有消费,显示其高活跃度 运营建议 :在高峰时段前1小时(18:00)推送限时折扣,转化率最高 2.3 商品类型偏好分析 def plot_item_preference(): """绘制商品类型偏好""" fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6)) # 1. 各玩家类型购买的商品类型分布 item_by_player = df_transactions.groupby(['player_type', 'item_type']).size().unstack(fill_value=0) item_by_player_pct = item_by_player.div(item_by_player.sum(axis=1), axis=0) * 100 # 绘制热力图 im = ax1.imshow(item_by_player_pct.values, cmap='YlOrRd', aspect='auto') ax1.set_xticks(range(len(item_by_player_pct.columns))) ax1.set_xticklabels(item_by_player_pct.columns, rotation=45) ax1.set_yticks(range(len(item_by_player_pct.index))) ax1.set_yticklabels(item_by_player_pct.index) ax1.set_title('商品类型偏好热力图 (%)', fontsize=14, fontweight='bold') # 添加数值标签 for i in range(len(item_by_player_pct.index)): for j in range(len(item_by_player_pct.columns)): text = ax1.text(j, i, f'{item_by_player_pct.iloc[i, j]:.1f}', ha="center", va="center", color="black", fontsize=9) # 2. 平均交易金额对比 avg_price_by_item = df_transactions.groupby('item_type')['price'].mean().sort_values(ascending=False) bars = ax2.bar(avg_price_by_item.index, avg_price_by_item.values, color=['#FF5722', '#2196F3', '#4CAF50', '#9C27B0', '#FF9800']) ax2.set_title('各商品类型平均交易金额', fontsize=14, fontweight='bold') ax2.set_ylabel('平均价格 ($)') ax2.tick_params(axis='x', rotation=45) # 添加数值标签 for bar, value in zip(bars, avg_price_by_item.values): ax2.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 0.1, f'${value:.2f}', ha='center', va='bottom', fontweight='bold') plt.tight_layout() plt.show() plot_item_preference() 分析洞察 : Bundle(捆绑包) :平均价格最高,适合大额付费用户 BattlePass :性价比高,是提升留存和转化的核心商品 Energy(体力) :单价低但购买频次高,适合小额付费用户 Skin(皮肤) :中等价格,外观党最爱,适合中额付费用户 3. 货币学分析 3.1 货币获取与消耗平衡性 经济系统平衡性的核心是确保货币的获取与消耗保持动态平衡,避免通货膨胀或通货紧缩。 def plot_currency_balance(): """绘制货币平衡性分析""" fig, axes = plt.subplots(2, 2, figsize=(16, 12)) axes = axes.flatten() # 1. 金币获取与消耗对比(按玩家类型) gold_balance = df_currency.groupby('player_type').agg({ 'gold_earned': 'sum', 'gold_spent': 'sum' }) x = np.arange(len(gold_balance.index)) width = 0.35 axes[0].bar(x - width/2, gold_balance['gold_earned'], width, label='金币获取', color='#4CAF50', alpha=0.8) axes[0].bar(x + width/2, gold_balance['gold_spent'], width, label='金币消耗', color='#FF5722', alpha=0.8) axes[0].set_title('金币获取 vs 消耗 (按玩家类型)', fontsize=14, fontweight='bold') axes[0].set_ylabel('数量') axes[0].set_xticks(x) axes[0].set_xticklabels(gold_balance.index) axes[0].legend() axes[0].grid(True, alpha=0.3, axis='y') # 添加平衡性指标 balance_ratio = gold_balance['gold_spent'] / gold_balance['gold_earned'] for i, ratio in enumerate(balance_ratio): axes[0].text(i, gold_balance['gold_earned'].iloc[i] * 1.05, f'消耗率: {ratio:.2f}', ha='center', fontsize=9, color='blue') # 2. 钻石获取与消耗对比 diamond_balance = df_currency.groupby('player_type').agg({ 'diamond_earned': 'sum', 'diamond_spent': 'sum' }) axes[1].bar(x - width/2, diamond_balance['diamond_earned'], width, label='钻石获取', color='#2196F3', alpha=0.8) axes[1].bar(x + width/2, diamond_balance['diamond_spent'], width, label='钻石消耗', color='#FF5722', alpha=0.8) axes[1].set_title('钻石获取 vs 消耗 (按玩家类型)', fontsize=14, fontweight='bold') axes[1].set_ylabel('数量') axes[1].set_xticks(x) axes[1].set_xticklabels(diamond_balance.index) axes[1].legend() axes[1].grid(True, alpha=0.3, axis='y') # 3. 货币流通速度(每日) # 模拟每日活跃玩家的货币流动 daily_gold_flow = df_currency['gold_earned'].sum() / 30 # 假设30天 daily_diamond_flow = df_currency['diamond_earned'].sum() / 30 flow_data = [daily_gold_flow, daily_diamond_flow] flow_labels = ['金币', '钻石'] bars = axes[2].bar(flow_labels, flow_data, color=['#4CAF50', '#2196F3'], alpha=0.8) axes[2].set_title('日均货币流通量', fontsize=14, fontweight='bold') axes[2].set_ylabel('数量') for bar, value in zip(bars, flow_data): axes[2].text(bar.get_x() + bar.get_width()/2., bar.get_height() + 10, f'{value:.0f}', ha='center', va='bottom', fontweight='bold') # 4. 货币储备分析(获取-消耗) net_gold = df_currency['gold_earned'].sum() - df_currency['gold_spent'].sum() net_diamond = df_currency['diamond_earned'].sum() - df_currency['diamond_spent'].sum() net_data = [net_gold, net_diamond] colors = ['#4CAF50' if x >= 0 else ‘#FF5722′ for x in net_data]

bars = axes[3].bar(flow_labels, net_data, color=colors, alpha=0.8)
axes[3].axhline(y=0, color=’black’, linestyle=’-‘, linewidth=0.8)
axes[3].set_title(‘净货币储备 (获取-消耗)’, fontsize=14, fontweight=’bold’)
axes[3].set_ylabel(‘净数量’)

for bar, value in zip(bars, net_data):
axes[3].text(bar.get_x() + bar.get_width()/2.,
value + (10 if value >= 0 else -20),
f'{value:.0f}’, ha=’center’, va=’bottom’ if value >= 0 else ‘top’,
fontweight=’bold’, color=’black’)

plt.tight_layout()
plt.show()

plot_currency_balance()
平衡性评估
:
金币
:如果消耗率 < 0.8,说明金币获取过多,可能导致通货膨胀 钻石 :如果消耗率 > 1.0,说明钻石获取不足,可能抑制消费
理想状态
:消耗率在0.85-0.95之间,保持轻微通胀以激励玩家获取更多货币
3.2 通货膨胀率计算与可视化
def plot_inflation_analysis():
“””绘制通货膨胀分析”””
fig, ax = plt.subplots(figsize=(14, 8))

# 模拟时间序列数据(30天)
dates = pd.date_range(start=’2024-01-01′, periods=30, freq=’D’)

# 模拟基础物价指数(100为基准)
base_price_index = 100

# 根据货币净增发计算通胀率
# 假设每天货币净增发导致物价上涨
daily_net_gold = df_currency[‘gold_earned’].sum() / 30 – df_currency[‘gold_spent’].sum() / 30
daily_net_diamond = df_currency[‘diamond_earned’].sum() / 30 – df_currency[‘diamond_spent’].sum() / 30

# 通胀率计算(简化模型)
inflation_rate_gold = (daily_net_gold / (df_currency[‘gold_earned’].sum() / 30)) * 100
inflation_rate_diamond = (daily_net_diamond / (df_currency[‘diamond_earned’].sum() / 30)) * 100

# 生成时间序列
gold_inflation = base_price_index * (1 + inflation_rate_gold/100)**np.arange(30)
diamond_inflation = base_price_index * (1 + inflation_rate_diamond/100)**np.arange(30)

# 绘制
ax.plot(dates, gold_inflation, label=’金币通胀指数’, color=’#4CAF50′, linewidth=2, marker=’o’, markersize=4)
ax.plot(dates, diamond_inflation, label=’钻石通胀指数’, color=’#2196F3′, linewidth=2, marker=’s’, markersize=4)
ax.axhline(y=base_price_index, color=’gray’, linestyle=’–‘, alpha=0.7, label=’基准线 (100)’)

ax.set_title(’30天货币通胀趋势分析’, fontsize=16, fontweight=’bold’)
ax.set_xlabel(‘日期’, fontsize=12)
ax.set_ylabel(‘物价指数’, fontsize=12)
ax.legend()
ax.grid(True, alpha=0.3)

# 格式化x轴日期
ax.xaxis.set_major_formatter(mdates.DateFormatter(‘%m-%d’))
plt.xticks(rotation=45)

# 添加通胀率标签
ax.text(0.02, 0.95, f’日均金币通胀率: {inflation_rate_gold:.3f}%’,
transform=ax.transAxes, fontsize=10,
bbox=dict(boxstyle=”round,pad=0.3″, facecolor=”#4CAF50″, alpha=0.2))
ax.text(0.02, 0.88, f’日均钻石通胀率: {inflation_rate_diamond:.3f}%’,
transform=ax.transAxes, fontsize=10,
bbox=dict(boxstyle=”round,pad=0.3″, facecolor=”#2196F3″, alpha=0.2))

plt.tight_layout()
plt.show()

plot_inflation_analysis()
通胀控制策略
:
高通胀(>1%)
:增加消耗途径,如限时商店、强化失败消耗、排行榜税收
低通胀(<0.1%) :增加获取途径,如日常任务奖励、登录奖励 负通胀 :立即增加货币投放,避免经济停滞 4. 经济系统平衡性研究 4.1 玩家生命周期价值(LTV)分析 def plot_ltv_analysis(): """绘制LTV分析""" fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6)) # 1. 各玩家类型的平均LTV ltv_by_type = df_players.groupby('player_type')['total_spending'].agg(['mean', 'median', 'std']) # 绘制带误差线的柱状图 colors = ['#E0E0E0', '#4CAF50', '#2196F3', '#FF5722'] bars = ax1.bar(ltv_by_type.index, ltv_by_type['mean'], yerr=ltv_by_type['std'], capsize=5, color=colors, alpha=0.8, error_kw={'elinewidth': 2, 'ecolor': 'black', 'capthick': 2}) ax1.set_title('各玩家类型平均LTV (生命周期价值)', fontsize=14, fontweight='bold') ax1.set_ylabel('平均消费金额 ($)') ax1.grid(True, alpha=0.3, axis='y') # 添加数值标签 for bar, value in zip(bars, ltv_by_type['mean'].values): ax1.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 1, f'${value:.1f}', ha='center', va='bottom', fontweight='bold') # 2. LTV分布直方图(按玩家类型) for i, ptype in enumerate(df_players['player_type'].unique()): data = df_players[df_players['player_type'] == ptype]['total_spending'] if len(data) > 0:
ax2.hist(data, bins=20, alpha=0.6, label=ptype, color=colors[i], density=True)

ax2.set_title(‘LTV分布密度图’, fontsize=14, fontweight=’bold’)
ax2.set_xlabel(‘消费金额 ($)’)
ax2.set_ylabel(‘密度’)
ax2.legend()
ax2.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

plot_ltv_analysis()
4.2 经济系统健康度仪表板
def create_economic_dashboard():
“””创建经济系统健康度仪表板”””
fig = plt.figure(figsize=(18, 12))
gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3)

# 1. 收入结构饼图
ax1 = fig.add_subplot(gs[0, 0])
revenue_by_type = df_players.groupby(‘player_type’)[‘total_spending’].sum()
colors = [‘#E0E0E0’, ‘#4CAF50’, ‘#2196F3’, ‘#FF5722′]
wedges, texts, autotexts = ax1.pie(revenue_by_type.values, labels=revenue_by_type.index,
autopct=’%1.1f%%’, colors=colors, startangle=90)
ax1.set_title(‘收入结构’, fontweight=’bold’)

# 2. 货币平衡性
ax2 = fig.add_subplot(gs[0, 1])
gold_balance = df_currency[‘gold_earned’].sum() – df_currency[‘gold_spent’].sum()
diamond_balance = df_currency[‘diamond_earned’].sum() – df_currency[‘diamond_spent’].sum()

balance_data = [gold_balance, diamond_balance]
balance_labels = [‘金币’, ‘钻石’]
colors_balance = [‘#4CAF50’ if x >= 0 else ‘#FF5722′ for x in balance_data]

bars = ax2.bar(balance_labels, balance_data, color=colors_balance, alpha=0.8)
ax2.axhline(y=0, color=’black’, linestyle=’-‘, linewidth=0.8)
ax2.set_title(‘货币净储备’, fontweight=’bold’)
ax2.set_ylabel(‘净数量’)

for bar, value in zip(bars, balance_data):
ax2.text(bar.get_x() + bar.get_width()/2.,
value + (50 if value >= 0 else -100),
f'{value:.0f}’, ha=’center’, va=’bottom’ if value >= 0 else ‘top’,
fontweight=’bold’)

# 3. 消费转化率
ax3 = fig.add_subplot(gs[0, 2])
paying_players = len(df_players[df_players[‘total_spending’] > 0])
total_players = len(df_players)
conversion_rate = paying_players / total_players * 100

ax3.pie([conversion_rate, 100-conversion_rate],
labels=[‘付费玩家’, ‘免费玩家’],
autopct=’%1.1f%%’,
colors=[‘#FF5722’, ‘#E0E0E0′],
startangle=90)
ax3.set_title(f’付费转化率\n({conversion_rate:.1f}%)’, fontweight=’bold’)

# 4. 商品销售分布
ax4 = fig.add_subplot(gs[1, :2])
item_sales = df_transactions[‘item_type’].value_counts()
bars = ax4.barh(item_sales.index, item_sales.values, color=’#2196F3′, alpha=0.8)
ax4.set_title(‘商品销售量分布’, fontweight=’bold’)
ax4.set_xlabel(‘销售数量’)

for bar, value in zip(bars, item_sales.values):
ax4.text(bar.get_width() + 10, bar.get_y() + bar.get_height()/2.,
f'{value}’, va=’center’, fontweight=’bold’)

# 5. 收入时间趋势
ax5 = fig.add_subplot(gs[1, 2])
daily_revenue = df_transactions.groupby(df_transactions[‘transaction_date’].dt.date)[‘price’].sum()
ax5.plot(daily_revenue.index, daily_revenue.values, color=’#FF5722′, linewidth=2, marker=’o’, markersize=3)
ax5.set_title(‘日收入趋势’, fontweight=’bold’)
ax5.set_ylabel(‘收入 ($)’)
ax5.tick_params(axis=’x’, rotation=45)
ax5.grid(True, alpha=0.3)

# 6. 玩家活跃度与消费关系
ax6 = fig.add_subplot(gs[2, :])
# 模拟活跃度数据(基于等级和注册时间)
df_players[‘days_since_reg’] = (datetime.now() – df_players[‘registration_date’]).dt.days
df_players[‘activity_score’] = df_players[‘level’] * np.log1p(df_players[‘days_since_reg’])

# 绘制散点图
scatter = ax6.scatter(df_players[‘activity_score’], df_players[‘total_spending’],
c=df_players[‘player_type’].astype(‘category’).cat.codes,
cmap=’viridis’, alpha=0.6, s=50)

ax6.set_title(‘活跃度 vs 消费金额 (颜色代表玩家类型)’, fontweight=’bold’)
ax6.set_xlabel(‘活跃度评分’)
ax6.set_ylabel(‘消费金额 ($)’)
ax6.grid(True, alpha=0.3)

# 添加颜色条
cbar = plt.colorbar(scatter, ax=ax6)
cbar.set_ticks([0, 1, 2, 3])
cbar.set_ticklabels([‘Free’, ‘Minnow’, ‘Dolphin’, ‘Whale’])

plt.suptitle(‘游戏经济系统健康度仪表板’, fontsize=20, fontweight=’bold’, y=0.995)
plt.show()

create_economic_dashboard()
5. 高级分析:预测与优化建议
5.1 玩家流失预警模型
def plot_churn_prediction():
“””绘制流失预警分析”””
fig, ax = plt.subplots(figsize=(14, 8))

# 基于消费频率和最近消费时间预测流失风险
# 模拟:最近30天无消费且活跃度低的玩家视为高流失风险

# 计算每个玩家的最近消费时间
latest_transactions = df_transactions.groupby(‘player_id’)[‘transaction_date’].max()
df_players[‘last_transaction’] = df_players[‘player_id’].map(latest_transactions)
df_players[‘days_since_last_purchase’] = (datetime.now() – df_players[‘last_transaction’]).dt.days.fillna(365)

# 计算消费频率
purchase_count = df_transactions.groupby(‘player_id’).size()
df_players[‘purchase_frequency’] = df_players[‘player_id’].map(purchase_count).fillna(0)

# 定义流失风险
def get_churn_risk(row):
if row[‘player_type’] == ‘Free’:
return ‘Low’ # 免费玩家不计算流失
if row[‘days_since_last_purchase’] > 30 and row[‘purchase_frequency’] < 2: return 'High' elif row['days_since_last_purchase'] > 14:
return ‘Medium’
else:
return ‘Low’

df_players[‘churn_risk’] = df_players.apply(get_churn_risk, axis=1)

# 绘制风险分布
risk_counts = df_players[df_players[‘player_type’] != ‘Free’][‘churn_risk’].value_counts()
colors = {‘Low’: ‘#4CAF50’, ‘Medium’: ‘#FF9800’, ‘High’: ‘#FF5722’}

bars = ax.bar(risk_counts.index, risk_counts.values,
color=[colors[r] for r in risk_counts.index], alpha=0.8)

ax.set_title(‘付费玩家流失风险分布’, fontsize=16, fontweight=’bold’)
ax.set_ylabel(‘玩家数量’)
ax.set_xlabel(‘风险等级’)

for bar, value in zip(bars, risk_counts.values):
ax.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 1,
f'{value}\n({value/risk_counts.sum()*100:.1f}%)’,
ha=’center’, va=’bottom’, fontweight=’bold’)

# 添加行动建议
high_risk_pct = risk_counts.get(‘High’, 0) / risk_counts.sum() * 100
if high_risk_pct > 20:
action = “立即启动召回活动!”
color = ‘#FF5722’
elif high_risk_pct > 10:
action = “准备召回策略”
color = ‘#FF9800’
else:
action = “维持现状”
color = ‘#4CAF50′

ax.text(0.02, 0.95, f’行动建议: {action}\n高风险玩家占比: {high_risk_pct:.1f}%’,
transform=ax.transAxes, fontsize=11, fontweight=’bold’,
bbox=dict(boxstyle=”round,pad=0.5″, facecolor=color, alpha=0.3))

plt.tight_layout()
plt.show()

plot_churn_prediction()
5.2 经济系统优化建议生成器
def generate_optimization_report():
“””生成经济系统优化报告”””
print(“=”*60)
print(“游戏经济系统优化报告”)
print(“=”*60)

# 1. 收入分析
total_revenue = df_players[‘total_spending’].sum()
avg_revenue_per_paying = df_players[df_players[‘total_spending’] > 0][‘total_spending’].mean()
conversion_rate = len(df_players[df_players[‘total_spending’] > 0]) / len(df_players) * 100

print(f”\n📊 收入概览:”)
print(f” 总收入: ${total_revenue:,.2f}”)
print(f” 付费玩家平均收入: ${avg_revenue_per_paying:.2f}”)
print(f” 付费转化率: {conversion_rate:.1f}%”)

# 2. 货币平衡性
gold_balance = df_currency[‘gold_earned’].sum() – df_currency[‘gold_spent’].sum()
diamond_balance = df_currency[‘diamond_earned’].sum() – df_currency[‘diamond_spent’].sum()

print(f”\n💰 货币平衡性:”)
print(f” 金币净储备: {gold_balance:.0f} (消耗率: {df_currency[‘gold_spent’].sum()/df_currency[‘gold_earned’].sum():.2f})”)
print(f” 钻石净储备: {diamond_balance:.0f} (消耗率: {df_currency[‘diamond_spent’].sum()/df_currency[‘diamond_earned’].sum():.2f})”)

# 3. 商品表现
item_performance = df_transactions.groupby(‘item_type’).agg({
‘price’: [‘count’, ‘sum’]
}).round(2)
item_performance.columns = [‘销售次数’, ‘总收入’]

print(f”\n📦 商品表现:”)
print(item_performance.to_string())

# 4. 优化建议
print(f”\n💡 优化建议:”)

# 检查通胀
gold_inflation = gold_balance / df_currency[‘gold_earned’].sum()
if gold_inflation > 0.2:
print(” ⚠️ 金币通胀风险高: 建议增加金币消耗途径(如装备强化、排行榜税收)”)
elif gold_inflation < 0.05: print(" ✅ 金币流通健康") # 检查转化率 if conversion_rate < 5: print(" ⚠️ 付费转化率低: 建议优化新手引导,增加首充优惠") elif conversion_rate > 15:
print(” ✅ 付费转化率优秀”)

# 检查鲸鱼用户依赖度
whale_revenue = df_players[df_players[‘player_type’] == ‘Whale’][‘total_spending’].sum()
whale_pct = whale_revenue / total_revenue * 100
if whale_pct > 60:
print(f” ⚠️ 收入过度依赖鲸鱼用户 ({whale_pct:.1f}%): 建议加强中额付费用户转化”)
else:
print(” ✅ 收入结构健康”)

# 商品建议
bundle_sales = item_performance.loc[‘Bundle’, ‘销售次数’]
if bundle_sales < item_performance['销售次数'].sum() * 0.2: print(" 💡 捆绑包销售占比低: 建议优化捆绑包内容或定价策略") print("\n" + "="*60) generate_optimization_report() 6. 实际应用案例与最佳实践 6.1 案例:某RPG游戏的经济系统崩溃与修复 问题识别 : 通过Matplotlib绘制的货币平衡图发现,金币在30天内净增发了500万,而消耗仅200万,导致物价指数上涨300%。 修复措施 : 紧急措施 :立即上线限时商店,消耗过剩金币 中期调整 :增加装备强化失败消耗机制 长期优化 :引入金币回收系统(如排行榜税收) 效果验证 : 修复后,通过Matplotlib绘制的通胀曲线显示,通胀率从每日2%降至0.3%,经济系统恢复健康。 6.2 最佳实践总结 数据驱动决策 :所有经济调整必须基于数据可视化分析 A/B测试 :新经济功能上线前,必须进行小范围A/B测试 实时监控 :建立实时仪表板,监控关键指标(通胀率、转化率、ARPU) 玩家反馈 :结合定量数据与定性反馈,全面评估经济系统 7. 总结 通过Matplotlib的强大可视化能力,我们可以将复杂的游戏经济数据转化为直观的洞察。从玩家分层到货币平衡,从消费模式到流失预警,每一个分析维度都能为游戏运营提供决策支持。 关键要点 : 玩家分层 :识别并重点维护高价值用户 货币平衡 :保持获取与消耗的动态平衡,避免通胀或通缩 商品优化 :基于数据调整商品结构和定价策略 预测分析 :提前识别风险,主动干预 游戏经济系统是一个动态演化的生态系统,需要持续的数据监控和优化。Matplotlib作为可视化工具,是连接数据与决策的桥梁,帮助游戏开发者构建健康、可持续的虚拟经济。 附录:完整代码整合 # 完整代码整合(可直接运行) import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime, timedelta # 设置中文字体 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 数据生成函数(见上文) # ... [此处省略数据生成函数,实际使用时请包含] # 所有绘图函数(见上文) # ... [此处省略绘图函数,实际使用时请包含] # 主程序 if __name__ == "__main__": print("开始游戏经济系统分析...") # 生成数据 df_players = generate_player_data(1000) df_transactions = generate_transaction_data(df_players, 5000) df_currency = generate_currency_flow(df_players) # 执行所有分析 plot_player_distribution() plot_consumption_pattern() plot_item_preference() plot_currency_balance() plot_inflation_analysis() plot_ltv_analysis() create_economic_dashboard() plot_churn_prediction() generate_optimization_report() print("\n分析完成!所有图表已生成。") 通过这个完整的分析框架,你可以根据实际游戏数据快速生成专业的经济分析报告,为游戏运营提供有力支持。