forked from agranitsa-star/Scientific-Data-Analyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlot.py
More file actions
784 lines (593 loc) · 29.5 KB
/
Plot.py
File metadata and controls
784 lines (593 loc) · 29.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
class PlotWindow:
def __init__(self, parent, columns_data):
self.parent = parent
self.columns_data = columns_data.copy()
self.column_names = list(columns_data.keys())
self.plot_types = {
"line": "Линия",
"scatter": "Точки",
"histogram": "Гистограмма"
}
self.current_plot_type = "line"
self.error_settings = {'enabled': False, 'num_bars': 30}
self.approximation_settings = {
'enabled': False,
'degree': 1
}
self.window = tk.Toplevel(parent.root if hasattr(parent, 'root') else parent)
self.window.title("Работа с графиками")
self.window.attributes('-fullscreen', True)
self.window.bind('<Escape>', lambda e: self.window.attributes('-fullscreen', False))
self.window.bind('<F11>', self.toggle_fullscreen)
self.current_fig = None
self.current_ax = None
self.current_canvas = None
self.current_plot_info = None
self.legend_visible = True
self.create_widgets()
def toggle_fullscreen(self, event=None):
is_fullscreen = self.window.attributes('-fullscreen')
self.window.attributes('-fullscreen', not is_fullscreen)
def create_widgets(self):
main_frame = ttk.Frame(self.window)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
self.plot_container = ttk.Frame(main_frame)
self.plot_container.pack(fill=tk.BOTH, expand=True)
self.initial_message = tk.Label(
self.plot_container,
text="Нажмите 'Добавить график' для начала работы",
font=("Arial", 16),
fg="gray"
)
self.initial_message.place(relx=0.5, rely=0.5, anchor="center")
control_frame = ttk.Frame(main_frame, height=60)
control_frame.pack(fill=tk.X, side=tk.BOTTOM, pady=(10, 0))
control_frame.pack_propagate(False)
button_frame = ttk.Frame(control_frame)
button_frame.pack(fill=tk.X, padx=10, pady=10)
ttk.Button(
button_frame,
text="💾 Экспорт",
command=self.export_plot
).pack(side=tk.RIGHT, padx=5)
ttk.Button(
button_frame,
text="➕ Добавить график",
command=self.add_plot_dialog
).pack(side=tk.RIGHT, padx=5)
self.approx_button = ttk.Button(
button_frame,
text="Аппроксимация: выкл",
command=self.show_approximation_dialog
)
self.approx_button.pack(side=tk.LEFT, padx=5)
self.error_button = ttk.Button(
button_frame,
text="Погрешности: выкл",
command=self.show_error_dialog
)
self.error_button.pack(side=tk.LEFT, padx=5)
self.plot_type_button = ttk.Button(
button_frame,
text=f"Тип: {self.plot_types[self.current_plot_type]}",
command=self.show_plot_type_dialog
)
self.plot_type_button.pack(side=tk.LEFT, padx=5)
self.legend_button = ttk.Button(
button_frame,
text="Спрятать легенду",
command=self.toggle_legend
)
self.legend_button.pack(side=tk.LEFT, padx=5)
def export_plot(self):
"""Экспортирует текущий график в PNG файл"""
if self.current_fig is None:
messagebox.showinfo("Информация", "Нет графика для экспорта")
return
file_path = filedialog.asksaveasfilename(
title="Сохранить график как PNG",
defaultextension=".png",
filetypes=[("PNG files", "*.png"), ("All files", "*.*")],
initialfile="graph.png"
)
if not file_path:
return
try:
self.current_fig.savefig(
file_path,
dpi=300,
bbox_inches='tight',
facecolor='white',
edgecolor='none'
)
messagebox.showinfo("Успех", f"График успешно сохранён!\n{file_path}")
except Exception as e:
messagebox.showerror("Ошибка экспорта", f"Не удалось сохранить график:\n{e}")
def show_approximation_dialog(self):
"""Диалог настройки аппроксимации"""
if self.current_plot_info is None:
messagebox.showinfo("Информация", "Сначала создайте график")
return
dialog = tk.Toplevel(self.window)
dialog.title("Аппроксимация")
dialog.geometry("250x170")
dialog.transient(self.window)
dialog.grab_set()
self.center_dialog_over_parent(dialog)
ttk.Label(dialog, text="Полиномиальная аппроксимация:",
font=("Arial", 10, "bold")).pack(pady=10)
enabled_var = tk.BooleanVar(value=self.approximation_settings['enabled'])
ttk.Checkbutton(dialog, text="Включить аппроксимацию",
variable=enabled_var).pack(pady=5)
ttk.Label(dialog, text="Степень полинома:").pack(pady=(5, 0))
degree_var = tk.StringVar(value=str(self.approximation_settings['degree']))
degree_spin = ttk.Spinbox(dialog, from_=1, to=10, textvariable=degree_var, width=10)
degree_spin.pack(pady=5)
def apply_approximation():
self.approximation_settings['enabled'] = enabled_var.get()
try:
degree = int(degree_var.get())
self.approximation_settings['degree'] = max(1, min(10, degree))
except ValueError:
self.approximation_settings['degree'] = 1
if self.approximation_settings['enabled']:
self.approx_button.config(text=f"Аппроксимация: вкл (ст.{self.approximation_settings['degree']})")
else:
self.approx_button.config(text="Аппроксимация: выкл")
self.redraw_current_plot_with_errors()
dialog.destroy()
button_frame = ttk.Frame(dialog)
button_frame.pack(pady=10)
ttk.Button(button_frame, text="Применить", command=apply_approximation).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="Отмена", command=dialog.destroy).pack(side=tk.LEFT, padx=5)
def show_error_dialog(self):
"""Диалог настройки погрешностей"""
if self.current_plot_info is None:
messagebox.showinfo("Информация", "Сначала создайте график")
return
dialog = tk.Toplevel(self.window)
dialog.title("Настройка погрешностей")
dialog.geometry("300x200")
dialog.transient(self.window)
dialog.grab_set()
self.center_dialog_over_parent(dialog)
ttk.Label(dialog, text="Погрешности:", font=("Arial", 10, "bold")).pack(pady=10)
enabled_var = tk.BooleanVar(value=self.error_settings.get('enabled', False))
ttk.Checkbutton(dialog, text="Включить погрешности", variable=enabled_var).pack(pady=5)
ttk.Label(dialog, text="Количество планок:").pack(pady=(10, 0))
num_bars_var = tk.StringVar(value=str(self.error_settings.get('num_bars', 30)))
num_bars_spin = ttk.Spinbox(dialog, from_=1, to=1000, textvariable=num_bars_var, width=10)
num_bars_spin.pack(pady=5)
def apply_errors():
self.error_settings['enabled'] = enabled_var.get()
try:
num_bars = int(num_bars_var.get())
self.error_settings['num_bars'] = max(1, min(1000, num_bars))
except ValueError:
self.error_settings['num_bars'] = 30
if self.error_settings['enabled']:
self.error_button.config(text=f"Погрешности: вкл ({self.error_settings['num_bars']})")
else:
self.error_button.config(text="Погрешности: выкл")
self.redraw_current_plot_with_errors()
dialog.destroy()
button_frame = ttk.Frame(dialog)
button_frame.pack(pady=10)
ttk.Button(button_frame, text="Применить", command=apply_errors).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="Отмена", command=dialog.destroy).pack(side=tk.LEFT, padx=5)
def toggle_legend(self):
if self.current_ax is None:
return
self.legend_visible = not self.legend_visible
if self.legend_visible:
self.current_ax.legend()
self.legend_button.config(text="Спрятать легенду")
else:
legend = self.current_ax.get_legend()
if legend:
legend.remove()
self.legend_button.config(text="Показать легенду")
self.current_canvas.draw()
def show_plot_type_dialog(self):
dialog = tk.Toplevel(self.window)
dialog.title("Выберите тип графика")
dialog.geometry("250x180")
dialog.transient(self.window)
dialog.grab_set()
self.center_dialog_over_parent(dialog)
ttk.Label(dialog, text="Тип графика:", font=("Arial", 10, "bold")).pack(pady=10)
type_var = tk.StringVar(value=self.current_plot_type)
for plot_type, display_name in self.plot_types.items():
ttk.Radiobutton(
dialog,
text=display_name,
variable=type_var,
value=plot_type
).pack(anchor=tk.W, padx=20, pady=2)
def confirm_type():
self.current_plot_type = type_var.get()
self.plot_type_button.config(text=f"Тип: {self.plot_types[self.current_plot_type]}")
dialog.destroy()
button_frame = ttk.Frame(dialog)
button_frame.pack(pady=10)
ttk.Button(button_frame, text="OK", command=confirm_type).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="Отмена", command=dialog.destroy).pack(side=tk.LEFT, padx=5)
def add_plot_dialog(self):
if not self.column_names:
messagebox.showinfo("Информация", "Нет данных для построения графика")
return
if self.current_fig is not None:
self.show_mode_selection()
else:
self.show_full_plot_dialog()
def show_mode_selection(self):
dialog = tk.Toplevel(self.window)
dialog.title("Выберите режим")
dialog.geometry("300x120")
dialog.transient(self.window)
dialog.grab_set()
self.center_dialog_over_parent(dialog)
ttk.Label(dialog, text="Выберите действие:", font=("Arial", 10, "bold")).pack(pady=10)
button_frame = ttk.Frame(dialog)
button_frame.pack(pady=10)
ttk.Button(button_frame, text="Новый график",
command=lambda: [dialog.destroy(), self.show_full_plot_dialog()]).pack(side=tk.LEFT, padx=5)
if self.current_plot_type != "histogram":
ttk.Button(button_frame, text="Добавить к текущему",
command=lambda: [dialog.destroy(), self.show_add_to_current_dialog()]).pack(side=tk.LEFT, padx=5)
else:
ttk.Button(button_frame, text="Добавить к текущему", state="disabled").pack(side=tk.LEFT, padx=5)
def show_full_plot_dialog(self):
dialog = tk.Toplevel(self.window)
dialog.title("Новый график")
dialog.geometry("400x420")
dialog.transient(self.window)
dialog.grab_set()
self.center_dialog_over_parent(dialog)
ttk.Label(dialog, text="Заголовок графика:").pack(pady=(10, 0))
title_var = tk.StringVar()
title_entry = ttk.Entry(dialog, textvariable=title_var)
title_entry.pack(pady=5, padx=20, fill=tk.X)
ttk.Label(dialog, text="Поддержка LaTeX: используйте $...$ для формул",
font=("Arial", 8), foreground="gray").pack()
ttk.Label(dialog, text="Подпись оси X:").pack(pady=(10, 0))
xlabel_var = tk.StringVar()
xlabel_entry = ttk.Entry(dialog, textvariable=xlabel_var)
xlabel_entry.pack(pady=5, padx=20, fill=tk.X)
ttk.Label(dialog, text="Подпись оси Y:").pack(pady=(10, 0))
ylabel_var = tk.StringVar()
ylabel_entry = ttk.Entry(dialog, textvariable=ylabel_var)
ylabel_entry.pack(pady=5, padx=20, fill=tk.X)
ttk.Label(dialog, text="Данные для графика:", font=("Arial", 10, "bold")).pack(pady=(10, 0))
ttk.Label(dialog, text="Ось X (данные):").pack(pady=(5, 0))
x_var = tk.StringVar(value=self.column_names[0])
x_combo = ttk.Combobox(dialog, textvariable=x_var, values=self.column_names, state="readonly")
x_combo.pack(pady=5, padx=20, fill=tk.X)
if self.current_plot_type != "histogram":
ttk.Label(dialog, text="Ось Y (данные):").pack(pady=(5, 0))
y_var = tk.StringVar(value=self.column_names[0])
y_combo = ttk.Combobox(dialog, textvariable=y_var, values=self.column_names, state="readonly")
y_combo.pack(pady=5, padx=20, fill=tk.X)
else:
y_var = None
def create_new_plot():
"""Создаёт новый график"""
self.error_settings = {'enabled': False, 'num_bars': 30}
self.approximation_settings = {'enabled': False, 'degree': 1}
self.update_error_button_text()
self.update_approx_button_text()
x_col = x_var.get()
y_col = y_var.get() if y_var else None
if x_col not in self.columns_data:
messagebox.showerror("Ошибка", "Колонка X не найдена")
return
if y_var and y_col not in self.columns_data:
messagebox.showerror("Ошибка", "Колонка Y не найдена")
return
x_data = self.columns_data[x_col]
y_data = self.columns_data[y_col] if y_col else None
if y_data is not None and len(x_data) != len(y_data):
messagebox.showerror("Ошибка", "Разная длина колонок")
return
title = title_var.get().strip() or f"{y_col or 'Histogram'} vs {x_col}"
xlabel = xlabel_var.get().strip() or x_col
ylabel = ylabel_var.get().strip() or (y_col or "Частота")
self.create_new_plot(x_data, y_data, x_col, y_col, title, xlabel, ylabel)
dialog.destroy()
button_frame = ttk.Frame(dialog)
button_frame.pack(pady=10)
ttk.Button(button_frame, text="Создать", command=create_new_plot).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="Отмена", command=dialog.destroy).pack(side=tk.LEFT, padx=5)
def show_add_to_current_dialog(self):
dialog = tk.Toplevel(self.window)
dialog.title("Добавить к текущему графику")
dialog.geometry("300x130")
dialog.transient(self.window)
dialog.grab_set()
self.center_dialog_over_parent(dialog)
ttk.Label(dialog, text="Добавить новую зависимость:", font=("Arial", 10, "bold")).pack(pady=5)
ttk.Label(dialog, text="Ось X (данные):").pack(pady=(5, 0))
x_var = tk.StringVar(value=self.column_names[0])
x_combo = ttk.Combobox(dialog, textvariable=x_var, values=self.column_names, state="readonly")
x_combo.pack(pady=5, padx=20, fill=tk.X)
ttk.Label(dialog, text="Ось Y (данные):").pack(pady=(5, 0))
y_var = tk.StringVar(value=self.column_names[0])
y_combo = ttk.Combobox(dialog, textvariable=y_var, values=self.column_names, state="readonly")
y_combo.pack(pady=5, padx=20, fill=tk.X)
def add_to_current():
x_col = x_var.get()
y_col = y_var.get()
if x_col not in self.columns_data or y_col not in self.columns_data:
messagebox.showerror("Ошибка", "Колонки не найдены")
return
x_data = self.columns_data[x_col]
y_data = self.columns_data[y_col]
if len(x_data) != len(y_data):
messagebox.showerror("Ошибка", "Разная длина колонок")
return
self.add_plot_to_current(x_data, y_data, x_col, y_col)
dialog.destroy()
button_frame = ttk.Frame(dialog)
button_frame.pack(pady=10)
ttk.Button(button_frame, text="Добавить", command=add_to_current).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="Отмена", command=dialog.destroy).pack(side=tk.LEFT, padx=5)
def create_new_plot(self, x_data, y_data, x_label, y_label, title, xlabel, ylabel):
"""Создаёт новый график"""
self.error_settings = {'enabled': False, 'num_bars': 30}
self.approximation_settings = {'enabled': False, 'degree': 1}
self.update_error_button_text()
self.update_approx_button_text()
if self.current_fig:
plt.close(self.current_fig)
for widget in self.plot_container.winfo_children():
widget.destroy()
fig, ax = plt.subplots(figsize=(12, 6))
self.current_plot_info = {
'x_data_label': x_label, 'y_data_label': y_label,
'title': title, 'xlabel': xlabel, 'ylabel': ylabel
}
if self.current_plot_type == "line":
if y_data is not None:
ax.plot(x_data, y_data, 'b-', linewidth=1.5,
label=f"{y_label} vs {x_label}")
else:
ax.plot(x_data, 'b-', linewidth=1.5,
label=x_label)
elif self.current_plot_type == "scatter":
if y_data is not None:
ax.scatter(x_data, y_data, c='blue', s=20, alpha=0.7,
label=f"{y_label} vs {x_label}")
else:
ax.scatter(range(len(x_data)), x_data, c='blue', s=20, alpha=0.7,
label=x_label)
elif self.current_plot_type == "histogram":
ax.hist(x_data, bins=30, alpha=0.7, color='blue', edgecolor='black',
label=x_label)
ax.set_title(title, fontsize=14)
ax.set_xlabel(xlabel, fontsize=12)
ax.set_ylabel(ylabel, fontsize=12)
ax.grid(True, alpha=0.3)
ax.legend()
canvas = FigureCanvasTkAgg(fig, self.plot_container)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
close_btn = tk.Button(
self.plot_container,
text="×",
command=self.close_current_plot,
font=("Arial", 16, "bold"),
bg="lightcoral",
fg="white",
width=2,
height=1,
bd=0,
highlightthickness=0
)
close_btn.place(relx=1.0, rely=0.0, anchor="ne", x=-8, y=8)
self.current_fig = fig
self.current_ax = ax
self.current_canvas = canvas
self.legend_visible = True
self.legend_button.config(text="Спрятать легенду")
def redraw_current_plot_with_errors(self):
"""Перерисовывает график с погрешностями и аппроксимацией"""
if self.current_plot_info is None:
return
info = self.current_plot_info.copy()
x_data = self.columns_data[info['x_data_label']]
y_data = self.columns_data[info['y_data_label']] if info['y_data_label'] else None
for widget in self.plot_container.winfo_children():
widget.destroy()
fig, ax = plt.subplots(figsize=(12, 6))
plot_label = f"{info['y_data_label']} vs {info['x_data_label']}" if info['y_data_label'] else info[
'x_data_label']
if y_data is not None:
if len(x_data) > 1000:
ax.plot(x_data, y_data, 'b-', linewidth=1.5, alpha=0.7, label=plot_label)
else:
ax.plot(x_data, y_data, 'b-', linewidth=1.5, marker='o', markersize=3, label=plot_label)
if self.error_settings.get('enabled', False):
xerr_val = np.std(x_data) / np.sqrt(len(x_data))
yerr_val = np.std(y_data) / np.sqrt(len(y_data))
num_bars = self.error_settings.get('num_bars', 30)
if num_bars >= len(x_data):
indices = np.arange(len(x_data))
else:
indices = np.linspace(0, len(x_data) - 1, num_bars, dtype=int)
x_plot = x_data[indices]
y_plot = y_data[indices]
xerr_plot = np.full(len(indices), xerr_val)
yerr_plot = np.full(len(indices), yerr_val)
ax.errorbar(x_plot, y_plot, xerr=xerr_plot, yerr=yerr_plot,
fmt='none', ecolor='red', capsize=3, alpha=0.8)
if self.approximation_settings.get('enabled', False):
degree = self.approximation_settings.get('degree', 1)
try:
sort_idx = np.argsort(x_data)
x_sorted = x_data[sort_idx]
y_sorted = y_data[sort_idx]
coeffs = np.polyfit(x_sorted, y_sorted, degree)
poly = np.poly1d(coeffs)
x_smooth = np.linspace(x_sorted.min(), x_sorted.max(), 200)
y_smooth = poly(x_smooth)
equation = self.format_polynomial_equation(coeffs, info['xlabel'], info['ylabel'])
approx_label = f"Аппрокс.: {equation}"
ax.plot(x_smooth, y_smooth, 'r--', linewidth=2, label=approx_label)
except Exception as e:
messagebox.showwarning("Ошибка аппроксимации",
f"Не удалось выполнить аппроксимацию:\n{e}")
else:
if self.current_plot_type == "histogram":
ax.hist(x_data, bins=30, alpha=0.7, color='blue', edgecolor='black',
label=plot_label)
else:
ax.plot(x_data, 'b-', linewidth=1.5, marker='o', markersize=3,
label=plot_label)
ax.set_title(info['title'], fontsize=14)
ax.set_xlabel(info['xlabel'], fontsize=12)
ax.set_ylabel(info['ylabel'], fontsize=12)
ax.grid(True, alpha=0.3)
ax.legend()
canvas = FigureCanvasTkAgg(fig, self.plot_container)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
close_btn = tk.Button(
self.plot_container,
text="×",
command=self.close_current_plot,
font=("Arial", 16, "bold"),
bg="lightcoral",
fg="white",
width=2,
height=1,
bd=0,
highlightthickness=0
)
close_btn.place(relx=1.0, rely=0.0, anchor="ne", x=-8, y=8)
self.current_fig = fig
self.current_ax = ax
self.current_canvas = canvas
def update_error_button_text(self):
"""Обновляет текст кнопки погрешностей"""
if self.error_settings.get('enabled', False):
self.error_button.config(text=f"Погрешности: вкл ({self.error_settings['num_bars']})")
else:
self.error_button.config(text="Погрешности: выкл")
def update_approx_button_text(self):
"""Обновляет текст кнопки аппроксимации"""
if self.approximation_settings.get('enabled', False):
self.approx_button.config(text=f"Аппроксимация: вкл (ст.{self.approximation_settings['degree']})")
else:
self.approx_button.config(text="Аппроксимация: выкл")
def format_polynomial_equation(self, coefficients, x_label, y_label):
"""
Форматирует полиномиальное уравнение для отображения в легенде
Args:
coefficients: массив коэффициентов [a_n, a_{n-1}, ..., a_0]
x_label: метка оси X
y_label: метка оси Y
Returns:
str: отформатированное уравнение
"""
if len(coefficients) == 0:
return "y = 0"
x_var = x_label.split(',')[0].strip() if ',' in x_label else x_label
y_var = y_label.split(',')[0].strip() if ',' in y_label else y_label
terms = []
degree = len(coefficients) - 1
for i, coeff in enumerate(coefficients):
current_degree = degree - i
if abs(coeff) < 1e-10:
if len(coefficients) == 1:
terms.append("0")
continue
if abs(coeff) == 1 and current_degree > 0:
coeff_str = "" if coeff > 0 else "-"
else:
if abs(coeff) >= 1e-3 and abs(coeff) < 1e4:
coeff_str = f"{coeff:.3g}"
else:
coeff_str = f"{coeff:.3e}"
if coeff > 0:
coeff_str = coeff_str
else:
coeff_str = coeff_str
if current_degree == 0:
term = coeff_str
elif current_degree == 1:
if coeff_str == "":
term = x_var
elif coeff_str == "-":
term = f"-{x_var}"
else:
term = f"{coeff_str}{x_var}"
else:
if coeff_str == "":
term = f"{x_var}^{current_degree}"
elif coeff_str == "-":
term = f"-{x_var}^{current_degree}"
else:
term = f"{coeff_str}{x_var}^{current_degree}"
terms.append(term)
if not terms:
equation_right = "0"
else:
equation_right = terms[0]
for term in terms[1:]:
if term.startswith('-'):
equation_right += f" - {term[1:]}"
else:
equation_right += f" + {term}"
if equation_right.startswith('+ '):
equation_right = equation_right[2:]
return f"{y_var} = {equation_right}"
def add_plot_to_current(self, x_data, y_data, x_label, y_label):
"""Добавляет новую линию к текущему графику"""
if self.current_ax is None or self.current_plot_type == "histogram":
return
if self.current_plot_type == "line":
self.current_ax.plot(x_data, y_data, linewidth=1.5, marker='s', markersize=3,
label=f"{y_label} vs {x_label}")
elif self.current_plot_type == "scatter":
self.current_ax.scatter(x_data, y_data, s=20, alpha=0.7,
label=f"{y_label} vs {x_label}")
if self.legend_visible:
self.current_ax.legend()
self.current_canvas.draw()
def close_current_plot(self):
if self.current_fig:
plt.close(self.current_fig)
self.current_fig = None
self.current_ax = None
self.current_canvas = None
self.current_plot_info = None
self.legend_visible = True
for widget in self.plot_container.winfo_children():
widget.destroy()
self.initial_message = tk.Label(
self.plot_container,
text="Нажмите 'Добавить график' для начала работы",
font=("Arial", 16),
fg="gray"
)
self.initial_message.place(relx=0.5, rely=0.5, anchor="center")
self.legend_button.config(text="Спрятать легенду")
def center_dialog_over_parent(self, dialog):
"""Центрирует диалог над основным окном"""
dialog.update_idletasks()
dialog_width = dialog.winfo_width()
dialog_height = dialog.winfo_height()
parent_x = self.window.winfo_x()
parent_y = self.window.winfo_y()
parent_width = self.window.winfo_width()
parent_height = self.window.winfo_height()
x = parent_x + (parent_width - dialog_width) // 2
y = parent_y + (parent_height - dialog_height) // 2
dialog.geometry(f'+{x}+{y}')