-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualizations.py
More file actions
390 lines (335 loc) · 14.5 KB
/
Copy pathvisualizations.py
File metadata and controls
390 lines (335 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import networkx as nx
from typing import List, Tuple, Dict, Any
import numpy as np
from plotly.subplots import make_subplots
from scipy import stats
from collections import Counter
class Visualizer:
def __init__(self, df: pd.DataFrame):
self.df = df
# Bilingual error messages
self.error_messages = {
'no_data': {
'en': 'No data available',
'ru': 'Данные отсутствуют'
},
'invalid_data': {
'en': 'Invalid data format',
'ru': 'Неверный формат данных'
},
'empty_data': {
'en': 'Dataset is empty',
'ru': 'Набор данных пуст'
},
'missing_column': {
'en': 'Required column missing: {}',
'ru': 'Отсутствует обязательный столбец: {}'
}
}
def _get_bilingual_message(self, key: str, *args) -> str:
"""Get bilingual error message"""
en_msg = self.error_messages[key]['en'].format(*args)
ru_msg = self.error_messages[key]['ru'].format(*args)
return f"{en_msg} / {ru_msg}"
def _create_empty_figure(self, message: str) -> go.Figure:
"""Create an empty figure with a bilingual message"""
fig = go.Figure()
fig.add_annotation(
text=message,
xref="paper", yref="paper",
x=0.5, y=0.5,
showarrow=False,
font=dict(size=14)
)
fig.update_layout(
showlegend=False,
xaxis={'showgrid': False, 'zeroline': False, 'visible': False},
yaxis={'showgrid': False, 'zeroline': False, 'visible': False}
)
return fig
def plot_topic_distribution(self, df: pd.DataFrame) -> go.Figure:
try:
if df.empty or 'rank' not in df.columns:
return self._create_empty_figure(
"No topic data available / Нет данных о темах"
)
# Calculate topic distribution
topic_counts = df['rank'].value_counts()
if topic_counts.empty:
return self._create_empty_figure(
"No valid topic data / Нет действительных данных о темах"
)
# Create bar chart
fig = px.bar(
x=topic_counts.index,
y=topic_counts.values,
labels={
'x': 'Topic / Тема',
'y': 'Number of Articles / Количество статей'
},
title='Article Distribution by Topic / Распределение статей по темам'
)
# Update layout
fig.update_layout(
height=400,
showlegend=False,
hovermode='x unified'
)
# Add hover template
fig.update_traces(
hovertemplate="<b>Topic:</b> %{x}<br><b>Articles:</b> %{y}<extra></extra>"
)
return fig
except Exception as e:
return self._create_empty_figure(
f"Error creating topic distribution / Ошибка создания распределения: {str(e)}"
)
def plot_trl_distribution(self, df: pd.DataFrame) -> go.Figure:
try:
if df.empty or 'TRL' not in df.columns:
return self._create_empty_figure(
"No TRL data available / Нет данных УГТ"
)
# Remove null values and convert to integers
trl_data = pd.to_numeric(df['TRL'], errors='coerce').dropna()
if trl_data.empty:
return self._create_empty_figure(
"No valid TRL data / Нет действительных данных УГТ"
)
# Convert to integers and get value counts
trl_counts = trl_data.astype(int).value_counts().sort_index()
# Create bar chart
fig = px.bar(
x=trl_counts.index,
y=trl_counts.values,
labels={
'x': 'TRL Level / Уровень УГТ',
'y': 'Number of Articles / Количество статей'
},
title='TRL Distribution / Распределение УГТ'
)
# Update layout
fig.update_layout(
height=400,
showlegend=False,
hovermode='x unified',
xaxis_tickmode='linear',
xaxis_tick0=1,
xaxis_dtick=1
)
# Add hover template
fig.update_traces(
hovertemplate="<b>TRL:</b> %{x}<br><b>Articles:</b> %{y}<extra></extra>"
)
return fig
except Exception as e:
return self._create_empty_figure(
f"Error creating TRL distribution / Ошибка создания распределения УГТ: {str(e)}"
)
def plot_categorical_tree(self, df: pd.DataFrame, column: str) -> go.Figure:
try:
if df.empty or column not in df.columns:
return self._create_empty_figure(
f"No {column} data available / Нет данных {column}"
)
# Get category counts and sort by frequency
category_counts = df[column].value_counts()
if category_counts.empty:
return self._create_empty_figure(
f"No valid {column} data / Нет действительных данных {column}"
)
# Create hierarchical data structure
fig = go.Figure(go.Treemap(
labels=[f"{cat}<br>({count})" for cat, count in category_counts.items()],
parents=["" for _ in range(len(category_counts))],
values=category_counts.values,
textinfo="label",
hovertemplate=(
"<b>Category:</b> %{label}<br>"
"<b>Count:</b> %{value}<br>"
"<extra></extra>"
)
))
# Update layout
fig.update_layout(
title=f"{column} Hierarchical Distribution / Иерархическое распределение {column}",
width=800,
height=600,
margin=dict(t=50, l=0, r=0, b=0)
)
return fig
except Exception as e:
return self._create_empty_figure(
f"Error creating hierarchical distribution / Ошибка создания иерархического распределения: {str(e)}"
)
def plot_text_analysis(self, df: pd.DataFrame, column: str) -> go.Figure:
try:
if df.empty or column not in df.columns:
return self._create_empty_figure(
f"No {column} data available / Нет данных {column}"
)
# Combine all text
text = ' '.join(df[column].dropna().astype(str))
if not text.strip():
return self._create_empty_figure(
f"No valid {column} data / Нет действительных данных {column}"
)
# Tokenize and count words
words = text.lower().split()
word_freq = Counter(words).most_common(20)
words, freqs = zip(*word_freq)
# Create bar chart
fig = px.bar(
x=words,
y=freqs,
title=f"Most Common Words in {column} / Самые частые слова в {column}",
labels={
'x': 'Word / Слово',
'y': 'Frequency / Частота'
}
)
# Update layout
fig.update_layout(
height=400,
showlegend=False,
hovermode='x unified'
)
return fig
except Exception as e:
return self._create_empty_figure(
f"Error analyzing {column} / Ошибка анализа {column}: {str(e)}"
)
def plot_correlation_matrix(self, df: pd.DataFrame, columns: List[str]) -> go.Figure:
try:
if df.empty or not columns:
return self._create_empty_figure(
"No data available for correlation / Нет данных для корреляции"
)
# Calculate correlation matrix
corr_matrix = df[columns].corr()
# Create heatmap
fig = px.imshow(
corr_matrix,
title="Correlation Matrix / Корреляционная матрица",
labels={
'x': 'Variable / Переменная',
'y': 'Variable / Переменная',
'color': 'Correlation / Корреляция'
},
color_continuous_scale='RdBu_r',
aspect='auto'
)
# Update layout
fig.update_layout(
height=600,
width=800
)
# Add correlation values as text
for i in range(len(columns)):
for j in range(len(columns)):
fig.add_annotation(
x=i,
y=j,
text=f"{corr_matrix.iloc[j, i]:.2f}",
showarrow=False,
font=dict(color='white' if abs(corr_matrix.iloc[j, i]) > 0.5 else 'black')
)
return fig
except Exception as e:
return self._create_empty_figure(
f"Error creating correlation matrix / Ошибка создания корреляционной матрицы: {str(e)}"
)
def plot_scatter(self, df: pd.DataFrame, x_column: str, y_column: str,
color_column: str = None, size_column: str = None) -> go.Figure:
try:
if df.empty or x_column not in df.columns or y_column not in df.columns:
return self._create_empty_figure(
f"No data available for scatter plot / Нет данных для диаграммы рассеяния"
)
# Create scatter plot
fig = px.scatter(
df,
x=x_column,
y=y_column,
color=color_column if color_column in df.columns else None,
size=size_column if size_column in df.columns else None,
title=f"{y_column} vs {x_column} / {y_column} против {x_column}",
labels={
x_column: f"{x_column}",
y_column: f"{y_column}",
'color': f"{color_column}" if color_column else None,
'size': f"{size_column}" if size_column else None
},
trendline="ols" if df[x_column].dtype.kind in 'biufc' and df[y_column].dtype.kind in 'biufc' else None
)
# Update layout with new responsive settings
fig.update_layout(
height=500,
margin=dict(l=50, r=50, t=50, b=50),
hovermode='closest',
template='plotly_white'
)
# Enhanced hover template
hover_template = (
f"<b>{x_column}:</b> %{{x}}<br>"
f"<b>{y_column}:</b> %{{y}}<br>"
)
if color_column:
hover_template += f"<b>{color_column}:</b> %{{color}}<br>"
if size_column:
hover_template += f"<b>{size_column}:</b> %{{size}}<br>"
hover_template += "<extra></extra>"
fig.update_traces(
hovertemplate=hover_template
)
return fig
except Exception as e:
return self._create_empty_figure(
f"Error creating scatter plot / Ошибка создания диаграммы рассеяния: {str(e)}"
)
def plot_mentions_distribution(self, search_results: Dict[str, Any]) -> go.Figure:
try:
if 'error' in search_results:
return self._create_empty_figure(
f"Error in search visualization: {search_results['error']}"
)
mentions = search_results.get('mentions_by_column', {})
if not mentions:
return self._create_empty_figure(
"No mentions found / Упоминания не найдены"
)
# Prepare data for visualization
columns = list(mentions.keys())
counts = [info['count'] for info in mentions.values()]
# Create bar chart
fig = px.bar(
x=columns,
y=counts,
title="Mentions Distribution / Распределение упоминаний",
labels={
'x': 'Field / Поле',
'y': 'Number of Mentions / Количество упоминаний'
}
)
# Update layout
fig.update_layout(
height=400,
showlegend=False,
hovermode='x unified'
)
# Add hover template
fig.update_traces(
hovertemplate=(
"<b>Field:</b> %{x}<br>"
"<b>Mentions:</b> %{y}<br>"
"<extra></extra>"
)
)
return fig
except Exception as e:
return self._create_empty_figure(
f"Error creating mentions visualization: {str(e)}"
)