Create 04_visualize_combined_results.py
Browse files
scripts/04_visualize_combined_results.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
import matplotlib.font_manager as fm
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
# ----------------------------------------
|
| 7 |
+
# 1. 분석 및 시각화 설정 (이곳을 수정하여 그래프를 변경할 수 있습니다)
|
| 8 |
+
# ----------------------------------------
|
| 9 |
+
# 1.1. 분석할 결과 유형을 선택하세요:
|
| 10 |
+
# - 'lexicon_frequency': 경험-기대 지수 (어휘 빈도 기반)
|
| 11 |
+
# - 'semantic_orientation': 과거-미래 의미 방향성 (단어 임베딩 기반)
|
| 12 |
+
# - 'neologism_rate': 신조어 출현율 (시간의 가속화)
|
| 13 |
+
ANALYSIS_TYPE = 'semantic_orientation'
|
| 14 |
+
|
| 15 |
+
# 1.2. 'semantic_orientation' 분석 시, 사용할 모델 타입을 선택하세요: 'word2vec' 또는 'fasttext'
|
| 16 |
+
MODEL_TYPE = 'word2vec'
|
| 17 |
+
|
| 18 |
+
# 1.3. 분석할 시간 단위를 선택하세요: 'yearly' 또는 'decade'
|
| 19 |
+
TIME_UNIT = 'yearly'
|
| 20 |
+
|
| 21 |
+
# ----------------------------------------
|
| 22 |
+
# 2. 설정에 따른 파일 경로 및 변수 동적 생성
|
| 23 |
+
# ----------------------------------------
|
| 24 |
+
output_dir = '/home/work/baro/koselleck_analysis_results'
|
| 25 |
+
input_file_path = ''
|
| 26 |
+
plot_title = ''
|
| 27 |
+
y_label = ''
|
| 28 |
+
|
| 29 |
+
if ANALYSIS_TYPE == 'lexicon_frequency':
|
| 30 |
+
input_file_path = os.path.join(output_dir, 'lexicon_frequency.csv')
|
| 31 |
+
plot_title = "'경험-기대 지수'의 시계열 변화"
|
| 32 |
+
y_label = "경험-기대 지수 (미래 지향 ↔ 과거 지향)"
|
| 33 |
+
TIME_UNIT = 'yearly' # 이 분석은 연도 단위만 존재
|
| 34 |
+
elif ANALYSIS_TYPE == 'semantic_orientation':
|
| 35 |
+
input_file_path = os.path.join(output_dir, f'{TIME_UNIT}_semantic_orientation_scores_{MODEL_TYPE}.csv')
|
| 36 |
+
plot_title = f"'과거-미래 의미 방향성'의 시계열 변화 ({MODEL_TYPE.upper()}, {TIME_UNIT})"
|
| 37 |
+
y_label = "의미 방향성 점수 (미래 지향 ↔ 과거 지향)"
|
| 38 |
+
elif ANALYSIS_TYPE == 'neologism_rate':
|
| 39 |
+
input_file_path = os.path.join(output_dir, f'{TIME_UNIT}_neologism_rate.csv')
|
| 40 |
+
plot_title = f"'시간의 가속화': {TIME_UNIT} 신조어 출현율 변화"
|
| 41 |
+
y_label = "신조어 출현율 (%)"
|
| 42 |
+
else:
|
| 43 |
+
raise ValueError("ANALYSIS_TYPE이 잘못 설정되었습니다.")
|
| 44 |
+
|
| 45 |
+
output_plot_path = os.path.join(output_dir, f'{ANALYSIS_TYPE}_{MODEL_TYPE}_{TIME_UNIT}_plot.png')
|
| 46 |
+
|
| 47 |
+
# ----------------------------------------
|
| 48 |
+
# 3. 데이터 로드 및 전처리
|
| 49 |
+
# ----------------------------------------
|
| 50 |
+
print(f"1. 분석 결과 파일 '{input_file_path}'을(를) 로드합니다.")
|
| 51 |
+
try:
|
| 52 |
+
df = pd.read_csv(input_file_path)
|
| 53 |
+
|
| 54 |
+
# '경험-기대 지수' 계산 (lexicon_frequency 경우)
|
| 55 |
+
if ANALYSIS_TYPE == 'lexicon_frequency':
|
| 56 |
+
denominator = df['experience_freq'] + df['expectation_freq']
|
| 57 |
+
df['value'] = ((df['expectation_freq'] - df['experience_freq']) / denominator).fillna(0)
|
| 58 |
+
df.rename(columns={'year': 'unit'}, inplace=True)
|
| 59 |
+
else:
|
| 60 |
+
df.rename(columns={df.columns[1]: 'value', df.columns[0]: 'unit'}, inplace=True)
|
| 61 |
+
|
| 62 |
+
# 데이터가 없는 연도/시대 처리를 위해 전체 시간 축 생성
|
| 63 |
+
if TIME_UNIT == 'yearly':
|
| 64 |
+
full_range = pd.DataFrame({'unit': range(1920, 2000)})
|
| 65 |
+
else: # decade
|
| 66 |
+
full_range = pd.DataFrame({'unit': range(1920, 2000, 10)})
|
| 67 |
+
|
| 68 |
+
df = pd.merge(full_range, df, on='unit', how='left')
|
| 69 |
+
|
| 70 |
+
except FileNotFoundError:
|
| 71 |
+
print(f"오류: '{input_file_path}'를 찾을 수 없습니다. 이전 단계의 분석을 먼저 실행해야 합니다.")
|
| 72 |
+
exit()
|
| 73 |
+
|
| 74 |
+
# ----------------------------------------
|
| 75 |
+
# 4. 시각화
|
| 76 |
+
# ----------------------------------------
|
| 77 |
+
print("\n2. 분석 결과를 시각화합니다.")
|
| 78 |
+
plt.style.use('ggplot')
|
| 79 |
+
fig, ax = plt.subplots(figsize=(20, 10))
|
| 80 |
+
|
| 81 |
+
# 분석 유형에 따라 다른 그래프 형태 적용
|
| 82 |
+
if ANALYSIS_TYPE in ['lexicon_frequency', 'semantic_orientation']:
|
| 83 |
+
ax.plot(df['unit'], df['value'], linewidth=2.5, marker='o', markersize=5, alpha=0.8)
|
| 84 |
+
ax.axhline(0, color='black', linestyle='--', linewidth=1, alpha=0.7)
|
| 85 |
+
ax.text(df['unit'].max() + 1, 0, '균형점', va='center', ha='left')
|
| 86 |
+
else: # neologism_rate
|
| 87 |
+
ax.bar(df['unit'], df['value'], alpha=0.7, width=df['unit'].diff().min() * 0.8 if TIME_UNIT == 'decade' else 0.8)
|
| 88 |
+
for i, val in enumerate(df['value']):
|
| 89 |
+
if pd.notna(val):
|
| 90 |
+
ax.text(df['unit'].iloc[i], val + 0.5, f"{val:.1f}%", ha='center')
|
| 91 |
+
|
| 92 |
+
# 공통 그래프 설정
|
| 93 |
+
ax.set_title(plot_title, fontsize=22, pad=25, weight='bold')
|
| 94 |
+
ax.set_xlabel("연도" if TIME_UNIT == 'yearly' else "시대", fontsize=16)
|
| 95 |
+
ax.set_ylabel(y_label, fontsize=16)
|
| 96 |
+
ax.tick_params(axis='x', labelsize=12, rotation=45)
|
| 97 |
+
ax.tick_params(axis='y', labelsize=12)
|
| 98 |
+
ax.grid(True, which='major', linestyle='--', linewidth=0.7)
|
| 99 |
+
|
| 100 |
+
# 데이터 부재 기간 표시 (연도별 그래프에만 적용)
|
| 101 |
+
if TIME_UNIT == 'yearly':
|
| 102 |
+
ax.axvspan(1941, 1944, color='gray', alpha=0.2, label='데이터 부재 기간 (1941-1944)')
|
| 103 |
+
ax.legend()
|
| 104 |
+
|
| 105 |
+
# 그래프 저장 및 출력
|
| 106 |
+
plt.tight_layout()
|
| 107 |
+
plt.savefig(output_plot_path, dpi=300, bbox_inches='tight')
|
| 108 |
+
print(f"\n생성된 그래프가 다음 경로에 저장되었습니다: {output_plot_path}")
|
| 109 |
+
plt.show()
|