-
Notifications
You must be signed in to change notification settings - Fork 0
/
plothelpers v0.py
2178 lines (1994 loc) · 86.6 KB
/
plothelpers v0.py
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from basichelpers import *
import colorlover as cl
import plotly.offline as plty
import plotly.graph_objs as go
import plotly.tools as tls
import plotly.figure_factory as ff
import matplotlib.pyplot as plt
from graphviz import Source
from sklearn.tree import export_graphviz
from sklearn.base import clone
## colorlover colors:
## https://plot.ly/ipython-notebooks/color-scales/
## plotly colors:
## 'Blackbody', 'Bluered', 'Blues', 'Earth', 'Electric', 'Greens', 'Greys','Hot',
## 'Jet', 'Picnic', 'Portland', 'Rainbow', 'RdBu', 'Reds', 'Viridis', 'YlGnBu', 'YlOrRd'
###############################################################################
## Constants
###############################################################################
line_styles = ['solid', 'longdashdot', 'longdash', 'dashdot', 'dash', 'dot']
###############################################################################
## Helper functions
###############################################################################
def make_colorscale(
clname: str = '3,qual,Paired',
n: Optional[int] = None,
reverse: bool = False) -> list:
cnum, ctype, cname = clname.split(',')
colors = cl.scales[cnum][ctype][cname]
if n and n > int(cnum):
colors = cl.to_rgb(cl.interp(colors, (n // 10 + 1) * 10))
else:
n = len(colors)
if reverse: colors = colors[::-1]
n_colors = len(colors)
step = n_colors // n
return [[i/(n-1), c] for i, c in enumerate(colors) if (i+1) % step == 0]
###############################################################################
## Plotly DataFrame plot functions
###############################################################################
## General ################################################
## Numerical - Histograms and Scatters #####################
def plotly_df_hists(
df: pd.DataFrame,
columns: Optional[Iterable[str]] = None,
subplot: bool = True,
ncols: Optional[int] = None,
barmode: str = 'group',
title: str = 'Bar charts',
**kwargs) -> None:
'''Docstring of `plotly_df_hists`
Plot histograms of DataFrame columns with plotly.
Basicly same with `plotly_hists`.
Args:
df: A pandas DataFrame.
columns: The column names. Optional.
If omitted, plot all numerical columns.
subplot: Whether to plot all data as subplots or not.
ncols: Number of subplots of every row.
Ignored when `subplots` is `False`.
If `None`, it's determined with `datasets`'s length.
barmode: 'stack', 'group', 'overlay' or 'relative'.
Ignored when `subplots` is `True`.
title: Save the plot with this name.
'''
try:
columns = list(columns)
except TypeError:
columns = df.select_dtypes(include=['number']).columns.tolist()
else:
for col in columns:
assert col in df, 'Column {} is not in given DataFrame.'.format(col)
datasets = df[columns]
return plotly_hists(datasets, orientation='vertical', names=columns, subplot=subplot, ncols=ncols, barmode=barmode, title=title, **kwargs)
def plotly_df_hist_grouped(
df: pd.DataFrame,
col: str,
groupby: str,
subplot: bool = False,
ncols: Optional[int] = None,
barmode: str = 'group',
normdist: bool = False,
title: Optional[str] = None,
**kwargs) -> None:
'''Docstring of `plotly_df_grouped_hist`
Plot histograms of given column grouped on the unique value of another column with plotly.
Args:
df: A pandas DataFrame.
col: Name of the column that the unique values of which
will be used for grouping.
groupby: Name of the column that will be grouped.
subplot: Whether to plot all data as subplots or not.
ncols: Number of subplots of every row.
normdist: Whether plot the normal distribution with mean
and std of given data.
title: Save the plot with this name.
'''
grouped = df.groupby(groupby)
groups = grouped.groups.keys()
datasets = [grouped.get_group(g)[col] for g in groups]
return plotly_hists(datasets, names=groups, subplot=subplot, ncols=ncols, barmode=barmode, title=(title or 'Histogram {} grouped by {}'.format(col, groupby)))
''' normal distribution
vals, data = grouped_col(df, col1, col2)
nrows = int(np.ceil(len(vals) / ncols))
fig = tls.make_subplots(rows=nrows, cols=ncols, subplot_titles=[str(v) for v in vals],
shared_yaxes=True, print_grid=False)
width = kwargs.get('width', 900)
height = kwargs.get('height', 700)
# layout = go.Layout(title='Histogram of {} - grouped by {}'.format(col2, col1), showlegend=False, width=width, height=height)
# for k in range(nrows):
# layout['yaxis{}'.format(k+1)]['title'] = 'Count'
layout = {'yaxis{}'.format(k+1): {'title': 'Count'} for k in range(nrows)}
layout.update(dict(
title='Histogram of {} - grouped by {}'.format(col2, col1),
showlegend=False, width=width, height=height
))
layout = go.Layout(layout)
for i in range(nrows):
for j in range(ncols):
try:
s = data[ncols * i + j]
except:
break
start = s.min()
end = s.max()
bin_size = (end - start) / kwargs.get('bin_num', 10)
if normdist:
tempfig = ff.create_distplot([s], [s.name], curve_type='normal', histnorm='', bin_size=bin_size)
for trace in tempfig['data']:
trace['xaxis'] = 'x{}'.format(i+1)
trace['yaxis'] = 'y{}'.format(j+1)
if trace['type'] == 'scatter':
trace['y'] = trace['y'] * s.count()
fig.append_trace(trace, i+1, j+1)
else:
trace = go.Histogram(x=s, xbins=dict(start=start, end=end, size=bin_size), name=s.name, autobinx=False)
fig.append_trace(trace, i+1, j+1)
fig['layout'].update(layout)
kwargs.get('save', False) and plty.plot(fig, filename=title+'.html', image_width=width, image_height=height, auto_open=False)
plty.iplot(fig)
'''
def plotly_df_boxes(
df: pd.DataFrame,
columns: Optional[Iterable[str]] = None,
subplot: bool = True,
ncols: Optional[int] = None,
title: str = 'Bar charts',
**kwargs) -> None:
'''Docstring of `plotly_df_boxes`
Plot box plots of DataFrame columns with plotly.
Basicly same with `plotly_boxes`.
Args:
df: A pandas DataFrame.
columns: The column names. Optional.
If omitted, plot all numerical columns.
subplot: Whether to plot all data as subplots or not.
ncols: Number of subplots of every row.
Ignored when `subplots` is `False`.
If `None`, it's determined with `datasets`'s length.
title: Save the plot with this name.
'''
try:
columns = list(columns)
except TypeError:
columns = df.select_dtypes(include=['number']).columns.tolist()
else:
for col in columns:
assert col in df, 'Column {} is not in given DataFrame.'.format(col)
datasets = df[columns]
return plotly_boxes(datasets, orientation='vertical', names=columns, subplot=subplot, ncols=ncols, title=title, **kwargs)
def plotly_df_box_grouped(
df: pd.DataFrame,
col: str,
groupby: str,
subplot: bool = False,
ncols: Optional[int] = None,
title: Optional[str] = None,
**kwargs) -> None:
'''Docstring of `plotly_df_grouped_box`
Plot box-plot of one column grouped by the unique value of another column with plotly.
Args:
df: A pandas DataFrame.
col: Name of the column that the unique values of which
will be used for grouping.
groupby: Name of the column that will be grouped.
title: Save the plot with this name.
'''
grouped = df.groupby(groupby)
groups = grouped.groups.keys()
datasets = [grouped.get_group(g)[col] for g in groups]
return plotly_boxes(datasets, names=groups, subplot=subplot, ncols=ncols, title=(title or 'Histogram {} grouped by {}'.format(col, groupby)))
# # df = df[[col1, col2]].dropna()
# # cols = df[col1].unique()
# # traces = [go.Box(y=df[df[col1] == col][col2], boxmean='sd', name=col) for col in cols]
# vals, data = grouped_col(df, col1, col2)
# traces = [go.Box(y=d, boxmean='sd', name=v) for v,d in zip(vals, data)]
# width = kwargs.get('width', 900)
# height = kwargs.get('height', 700)
# layout = go.Layout(
# title='{} boxes grouped by {}'.format(col2, col1),
# yaxis=dict(title=col2),
# xaxis=dict(title=col1),
# width=width,
# height=height
# )
# fig = go.Figure(data=traces, layout=layout)
# kwargs.get('save', False) and plty.plot(fig, filename=title+'.html', image_width=width, image_height=height, auto_open=False)
# plty.iplot(fig)
def plotly_df_scatter(
df: pd.DataFrame,
colx: str,
coly: str,
size: Union[str, float] = 6,
sizescale: int = 100,
color: str = None,
colorscale: Union[str, List[list]] = '10,div,RdYlBu',
title: str = 'DataFrame Scatter',
**kwargs) -> None:
'''Docstring of `plotly_scatter`
Plot scatter plot of two columns of given DataFrame with plotly.
Basicly same with `plotly_scatter`.
Args:
df: A pandas DataFrame.
colx: Name of column; x axis.
coly: Name of column; y axis.
size: Size of markers.
A column of given Dataframe, a float or a list.
When passed a column name, the column will be used
to determine the sizes of corresponding markers.
If passed an iterable, it must be the same length
as datasets.
sizescale: Ignored if `size` is a single value.
A function to scale `size` to more reasonable values.
color: Marker color. A column of given Dataframe, any
kind of valid color string, or a numeric list.
When passed a column name, the column will be used
to determine the colors of corresponding markers.
If list, the value will be used with `colorscale`.
colorscale: Ignored when `color` is not a list.
A list of `[percentage, color]` pairs, or a string
that can be passed to `make_colorscale`.
title: Save the plot with this name.
'''
assert colx in df, 'Column {} not in given dataframe'.format(colx)
assert coly in df, 'Column {} not in given dataframe'.format(coly)
x = df[colx].values
y = df[coly].values
if isinstance(size, str) and size in df:
size = df[size]
if isinstance(color, str) and color in df:
color = df[color]
return plotly_scatter(x, y, size, sizescale, color, colorscale, title, **kwargs)
def plotly_df_scatter_matrix(
df: pd.DataFrame,
columns: Optional[List[str]] = None,
size: Union[str, float] = 2,
sizescale: int = 100,
color: str = None,
colorscale: Union[str, list] = '10,div,RdYlBu',
title: str = 'Scatter Matrix',
**kwargs) -> None:
'''Docstring of `plotly_df_scatter`
Plot scatter matrix of any number of given columns with plotly.
Basicly same with `plotly_scatter_matrix`.
Args:
df: A pandas DataFrame.
columns: Columns' names for plotting.
If `None`, use all numerical columns.
size: Marker size. A column of given Dataframe, a float,
or a numerical list.
When passed a column name, the column will be used
to determine the sizes of corresponding markers.
If a list, it must be the same length as datasets.
sizescale: Ignored when `size` is a float.
Scale the Dataframe to fit markers' size to the plot.
color: Marker color. A column of given Dataframe, any
kind of valid color string, or a numerical list.
When passed a column name, the column will be used
to determine the colors of corresponding markers.
If list, the value will be used with `colorscale`.
colorscale: Ignored when `color` is not a column of
given Dataframe.
A list of `[percentage, color]` pairs, or a string
that can be passed to `make_colorscale`.
title: Save the plot with this name.
'''
try:
columns = list(columns)
except TypeError:
columns = df.select_dtypes(include=['number']).columns.tolist()
else:
for col in columns:
assert col in df, 'Column {} is not in given DataFrame.'.format(col)
if isinstance(size, str) and size in df:
size = df[size]
if isinstance(color, str) and color in df:
color = df[color]
datasets = df[columns]
return plotly_scatter_matrix(datasets, orientation='vertical', names=columns, size=size, sizescale=sizescale, color=color, colorscale=colorscale, title=title, **kwargs)
def plotly_df_clusters(
df: pd.DataFrame,
colx: str,
coly: str,
collabel: str,
names: dict = None,
sizes=6,
colorscale: Union[str, list] = '12,qual,Paired',
title: str = 'DataFrame 2D Clusters',
**kwargs) -> None:
'''Docstring of `plotly_df_2d_clusters`
Plot scatter plots of two columns grouped by the unique values
of a third column with plotly.
Basicly same with `plotly_clusters`.
Args:
df: A pandas DataFrame.
colx: The column name of x values.
coly: The column name of y values.
collabel: The column name to group x and y on which.
names: Lables' names. Optional.
sizes: A single number or a number list.
Marker sizes of each cluster.
colorscale: Colors of clusters.
A list of `[percentage, color]` pairs, or a string
that can be passed to `make_colorscale`.
title: Title of the plot.
'''
assert colx in df, 'Column {} not in given dataframe'.format(colx)
assert coly in df, 'Column {} not in given dataframe'.format(coly)
assert collabel in df, 'Column {} not in given dataframe'.format(collabel)
x = df[colx].values
y = df[coly].values
label = df[collabel].values
return plotly_clusters(x, y, label, names=names, sizes=sizes, colorscale=colorscale, title=title, **kwargs)
def plotly_df_qq_plots(
df: pd.DataFrame,
columns: Optional[List[str]] = None,
ncols: Optional[int] = None,
title: str = 'DaraFrame QQ plots',
**kwargs) -> None:
'''Docstring of `plotly_qq_plots`
Plot QQ-plots of all the given data with plotly.
Args:
datasets: A list of data to plot.
names: Data names corresponding to items in data. Optional.
ncols: Number of subplots of every row.
Ignored when `subplots` is `False`.
If `None`, it's determined with `datasets`'s length.
title: Save the plot with this name.
'''
try:
columns = list(columns)
except TypeError:
columns = df.select_dtypes(include=['number']).columns.tolist()
else:
for col in columns:
assert col in df, 'Column {} is not in given DataFrame.'.format(col)
datasets = df[columns]
return plotly_qq_plots(datasets, orientation='vertical', names=columns, ncols=ncols, title=title, **kwargs)
## Categorical - Bars and contingency tables #####################
def plotly_df_bars(
df: pd.DataFrame,
columns: Optional[Iterable[str]] = None,
subplot: bool = False,
ncols: Optional[int] = None,
barmode: str = 'group',
title: str = 'Bar charts',
**kwargs) -> None:
'''Docstring of `plotly_df_bars`
Plot bar charts of DataFrame columns with plotly.
Basicly same with `plotly_bars`.
Args:
df: A pandas DataFrame.
columns: The column names. Optional.
If omitted, plot all categorical columns.
subplot: Whether to plot all data as subplots or not.
ncols: Number of subplots of every row.
Ignored when `subplots` is `False`.
If `None`, it's determined with `datasets`'s length.
barmode: 'stack', 'group', 'overlay' or 'relative'.
Ignored when `subplots` is `True`.
title: Save the plot with this name.
'''
try:
columns = list(columns)
except TypeError:
columns = df.select_dtypes(include=[object]).columns.tolist()
else:
for col in columns:
assert col in df, 'Column {} is not in given DataFrame.'.format(col)
datasets = df[columns]
return plotly_bars(datasets, orientation='vertical', names=columns, subplot=subplot, ncols=ncols, barmode=barmode, title=title, **kwargs)
def plotly_df_crosstable(
df: pd.DataFrame,
columns: Optional[Iterable[str]] = None,
half: bool = False,
ttype: str = 'count',
title: str = 'DataFrame Contigency Table',
**kwargs) -> None:
'''Docstring of `plotly_df_crosstable`
Plot contigency table of two given columns with plotly heatmap.
Basicly same with `plotly_crosstable`
Args:
df: A pandas DataFrame.
columns: The column names. Optional.
If omitted, plot all categorical columns.
half: Stacked bar plot or heatmap.
ttype: Determines how the contigency table is calculated.
'count': The counts of every combination.
'percent': The percentage of every combination to the
sum of every rows.
Defaults to 'count'.
colorscale: Heatmap colorscale. Avaiable values are
'Blackbody', 'Bluered', 'Blues', 'Earth', 'Electric', 'Greens',
'Greys', 'Hot', 'Jet', 'Picnic', 'Portland', 'Rainbow', 'RdBu',
'Reds', 'Viridis', 'YlGnBu', 'YlOrRd'.
title: Save the plot with this name.
'''
try:
columns = list(columns)
except TypeError:
columns = df.select_dtypes(include=[object]).columns.tolist()
else:
for col in columns:
assert col in df, 'Column {} is not in given DataFrame.'.format(col)
datasets = df[columns]
return plotly_crosstable(datasets, orientation='vertical', names=columns, half=half, ttype=ttype, title=title, **kwargs)
def plotly_df_crosstable_stacked(
df: pd.DataFrame,
columns: Optional[Iterable[str]] = None,
half: bool = False,
ttype: str = 'count',
title: str = 'DataFrame Contigency Table',
**kwargs) -> None:
'''Docstring of `plotly_df_crosstable_stacked`
Plot contigency table of two given columns with plotly heatmap.
Basicly same with `plotly_crosstable_stacked`
Args:
df: A pandas DataFrame.
columns: The column names. Optional.
If omitted, plot all categorical columns.
half: Stacked bar plot or heatmap.
ttype: Determines how the contigency table is calculated.
'count': The counts of every combination.
'percent': The percentage of every combination to the
sum of every rows.
Defaults to 'count'.
colorscale: Heatmap colorscale. Avaiable values are
'Blackbody', 'Bluered', 'Blues', 'Earth', 'Electric', 'Greens',
'Greys', 'Hot', 'Jet', 'Picnic', 'Portland', 'Rainbow', 'RdBu',
'Reds', 'Viridis', 'YlGnBu', 'YlOrRd'.
title: Save the plot with this name.
'''
try:
columns = list(columns)
except TypeError:
columns = df.select_dtypes(include=[object]).columns.tolist()
else:
for col in columns:
assert col in df, 'Column {} is not in given DataFrame.'.format(col)
datasets = df[columns]
return plotly_crosstable_stacked(datasets, orientation='vertical', names=columns, half=half, ttype=ttype, title=title, **kwargs)
def plotly_df_chi_square_matrix(
df: pd.DataFrame,
columns: Optional[Iterable[str]] = None,
title: str = 'Chi-Square Matrix',
**kwargs) -> None:
'''Docstring of `plotly_df_chi_square_matrix`
Run chi-square test on every two columns of given pandas DataFrame,
with contigency tables calculated on the two columns.
Then plot the results as a matrix.
Args:
df: A pandas DataFrame.
columns: The column names. Optional.
If omitted, plot all categorical columns.
title: Save the plot with this name.
'''
try:
columns = list(columns)
except TypeError:
columns = df.select_dtypes(include=[object]).columns.tolist()
else:
for col in columns:
assert col in df, 'Column {} is not in given DataFrame.'.format(col)
datasets = df[columns]
return plotly_chi_square_matrix(datasets, orientation='vertical', names=columns, title=title, **kwargs)
###############################################################################
## Plotly Array plot functions
###############################################################################
## General ################################################
def plotly_describes(
data: list,
names: list = [],
title: str = 'Descriptive Statistics',
**kwargs) -> None:
'''Docstring of `plotly_describes`
Plot a table of descriptive statistics of given data with plotly.
Args:
data: A list of numerical data.
names: A list contains names corresponding to data.
title: Save the plot with this name.
'''
ndata = len(data)
names = names or ['']*ndata
describes = np.empty((12, ndata+1), dtype=object)
for i, d, n in zip(range(ndata), data, names):
des = advanced_describe(d, name=n)
if i == 0:
describes[0, 0] = 'Describes'
describes[1:, 0] = des[2:, 0]
describes[0, i+1] = des[0, 1]
describes[1:, i+1] = ['{:.2f}'.format(float(v)) for v in des[2:, 1]]
fig = ff.create_table(describes, index=True)
width = kwargs.get('width', 900)
height = kwargs.get('height', 700)
fig.layout.width = width
fig.layout.height = height
fig.layout.title = title
kwargs.get('save', False) and plty.plot(fig, filename=title+'.html', image_width=width, image_height=height, auto_open=False)
if kwargs.get('return_fig', False):
return fig
else:
plty.iplot(fig)
## Numerical - Histograms and Scatters #####################
def plotly_hists(
datasets: Union[list, np.array],
names: Optional[Iterable[str]] = None,
subplot: bool = False,
ncols: Optional[int] = None,
barmode: str = 'group',
title: str = 'Histogram',
**kwargs) -> None:
'''Docstring of `plotly_hists`
Plot histograms with plotly.
Args:
datasets: A list of data to plot.
names: Data names corresponding to items in data. Optional.
subplot: Whether to plot all data as subplots or not.
ncols: Number of subplots of every row.
Ignored when `subplots` is `False`.
If `None`, it's determined with `datasets`'s length.
barmode: 'stack', 'group', 'overlay' or 'relative'.
Ignored when `subplots` is `True`.
title: Save the plot with this name.
'''
width = kwargs.get('width', 900)
height = kwargs.get('height', 700)
layout = go.Layout(title=title, width=width, height=height)
layout.update(kwargs.get('layout', {}))
# preparation
datasets = np.array(datasets)
if kwargs.get('orientation', 'horizontal') == 'vertical':
datasets = np.array(datasets).T
ndata = datasets.shape[0]
if names is not None:
assert len(names) == ndata, 'Not enough names for data length {}. Given {}.'.format(ndata, len(names))
else:
names = ['trace{}'.format(i+1) for i in range(ndata)]
hist_common_layout = kwargs.get('hist_common_layout', {})
hist_unique_layouts = kwargs.get('hist_unique_layout', [{}]*ndata)
# make traces for every data row
traces = []
for data, name, hist_layout in zip(datasets, names, hist_unique_layouts):
start = np.min(data)
end = np.max(data)
bin_size = np.ptp(data) / kwargs.get('bin_num', 10)
if kwargs.get('horizontal', False):
trace = go.Histogram(y=data, xbins=dict(start=start, end=end, size=bin_size), name=name, **hist_layout, **hist_common_layout)
else:
trace = go.Histogram(x=data, xbins=dict(start=start, end=end, size=bin_size), name=name, **hist_layout, **hist_common_layout)
traces.append(trace)
if subplot:
if ncols is None:
nrows = int(np.floor(np.power(ndata, 0.5)))
ncols = int(np.ceil(ndata / nrows))
else:
nrows = int(np.ceil(ndata / ncols))
fig = tls.make_subplots(rows=nrows, cols=ncols, subplot_titles=names,
vertical_spacing=0.1, horizontal_spacing=0.1, print_grid=False)
for i, trace in enumerate(traces):
fig.append_trace(trace, i // ncols + 1, i % ncols + 1)
else:
if ndata > 1:
assert barmode in ['stack', 'group', 'overlay', 'relative'], 'Invalid barmode "{}".'.format(barmode)
layout.barmode = barmode
fig = go.Figure(data=traces)
fig['layout'].update(layout)
kwargs.get('save', False) and plty.plot(fig, filename=title+'.html', image_width=width, image_height=height, auto_open=False)
if kwargs.get('return_fig', False):
return fig
else:
plty.iplot(fig)
def plotly_boxes(
datasets: Union[list, np.array],
names: Optional[Iterable[str]] = None,
subplot: bool = False,
ncols: Optional[int] = None,
title: str = 'Histogram',
**kwargs) -> None:
'''Docstring of `plotly_hists`
Plot histograms with plotly.
Args:
datasets: A list of data to plot.
names: Data names corresponding to items in data. Optional.
subplot: Whether to plot all data as subplots or not.
ncols: Number of subplots of every row.
Ignored when `subplots` is `False`.
If `None`, it's determined with `datasets`'s length.
title: Save the plot with this name.
'''
width = kwargs.get('width', 900)
height = kwargs.get('height', 700)
layout = go.Layout(title=title, width=width, height=height)
layout.update(kwargs.get('layout', {}))
# preparation
datasets = np.array(datasets)
if kwargs.get('orientation', 'horizontal') == 'vertical':
datasets = np.array(datasets).T
ndata = datasets.shape[0]
if names is not None:
assert len(names) == ndata, 'Not enough names for data length {}. Given {}.'.format(ndata, len(names))
else:
names = ['trace{}'.format(i+1) for i in range(ndata)]
box_common_layout = kwargs.get('box_common_layout', {})
box_unique_layouts = kwargs.get('box_unique_layout', [{}]*ndata)
# make traces for every data row
traces = []
for data, name, box_layout in zip(datasets, names, box_unique_layouts):
if kwargs.get('horizontal', False):
trace = go.Box(x=data, boxmean='sd', name=name, **box_layout, **box_common_layout)
else:
trace = go.Box(y=data, boxmean='sd', name=name, **box_layout, **box_common_layout)
traces.append(trace)
if subplot:
if ncols is None:
nrows = int(np.floor(np.power(ndata, 0.5)))
ncols = int(np.ceil(ndata / nrows))
else:
nrows = int(np.ceil(ndata / ncols))
fig = tls.make_subplots(rows=nrows, cols=ncols, subplot_titles=names,
vertical_spacing=0.1, horizontal_spacing=0.1, print_grid=False)
for i, trace in enumerate(traces):
fig.append_trace(trace, i // ncols + 1, i % ncols + 1)
else:
fig = go.Figure(data=traces)
fig['layout'].update(layout)
kwargs.get('save', False) and plty.plot(fig, filename=title+'.html', image_width=width, image_height=height, auto_open=False)
if kwargs.get('return_fig', False):
return fig
else:
plty.iplot(fig)
def plotly_scatter(
x,
y,
size = 6,
sizescale: Optional[callable] = None,
color = None,
colorscale: Union[str, List[list]] = '10,div,RdYlBu',
title: str = 'Scatter',
**kwargs) -> None:
'''Docstring of `plotly_scatter`
Plot scatters with plotly.
Args:
x: x axis.
y: y axis. `x` and `y` must have same length.
size: Size of markers. If passed an iterable, it must be
the same length as datasets.
sizescale: Ignored if `size` is a single value.
A function to scale `size` to more reasonable values.
color: Marker color. A numeric list or any
kind of valid color string.
If list, the value will be used with `colorscale`.
colorscale: Ignored when `color` is not a list.
A list of `[percentage, color]` pairs, or a string
that can be passed to `make_colorscale`.
title: Save the plot with this name.
'''
assert len(x) == len(y), 'Given data have different length. `x`:{}, `y`:{}'.format(len(x), len(y))
width = kwargs.get('width', 900)
height = kwargs.get('height', 700)
layout = go.Layout(title=title, width=width, height=height)
layout.update(kwargs.get('layout', {}))
if not isinstance(size, (int, float)):
sizescale = sizescale or (lambda array: (np.array(array) - np.min(array)) / np.ptp(array) * 30)
size = sizescale(size)
marker = dict(
opacity = kwargs.get('marker_opacity', 0.5),
size = size,
showscale = False,
line = dict(
width = kwargs.get('marker_line_width', 1),
color = kwargs.get('marker_line_color', 'rgb(0,0,0)')
)
)
if color is not None:
if not isinstance(color, str):
if isinstance(colorscale, str):
colorscale = make_colorscale(colorscale, reverse=kwargs.get('colorscale_reverse', False))
marker['colorscale'] = colorscale
marker['showscale'] = kwargs.get('showscale', True)
marker['color'] = color
trace = go.Scattergl(
x=x, y=y, mode='markers',
marker=marker
)
fig = go.Figure(data=[trace])
fig['layout'].update(layout)
kwargs.get('save', False) and plty.plot(fig, filename=title+'.html', image_width=width, image_height=height, auto_open=False)
if kwargs.get('return_fig', False):
return fig
else:
plty.iplot(fig)
def plotly_scatter_matrix(
datasets,
names: Optional[List[str]] = None,
size = 6,
sizescale: Optional[callable] = None,
color = None,
colorscale: Union[str, List[list]] = '10,div,RdYlBu',
title: str = 'Scatter Matrix',
**kwargs) -> None:
'''Docstring of `plotly_scatter_matrix`
Plot scatter matrix of any set of datasets with plotly.
The subplots from top left to bottom right on diagonal are replaced with histograms.
Args:
datasets: A list of data to plot.
names: Names corresponding to items in datasets. Optional.
size: Size of markers. If passed an iterable, it must be
the same length as datasets.
sizescale: Ignored if `size` is a single value.
A function to scale `size` to more reasonable values.
color: Marker color. A numeric list or any
kind of valid color string.
If list, the value will be used with `colorscale`.
colorscale: Ignored when `color` is not a list.
A list of `[percentage, color]` pairs, or a string
that can be passed to `make_colorscale`.
title: Save the plot with this name.
'''
width = kwargs.get('width', 900)
height = kwargs.get('height', 700)
layout = go.Layout(title=title, width=width, height=height)
layout.update(kwargs.get('layout', {}))
# preparation
datasets = np.array(datasets)
if kwargs.get('orientation', 'horizontal') == 'vertical':
datasets = np.array(datasets).T
ndata = datasets.shape[0]
if names is not None:
assert len(names) == ndata, 'Not enough names for data length {}. Given {}.'.format(ndata, len(names))
else:
names = ['trace{}'.format(i+1) for i in range(ndata)]
hist_common_layout = kwargs.get('hist_common_layout', {})
hist_unique_layouts = kwargs.get('hist_unique_layout', [{}]*ndata)
if not isinstance(size, (int, float)):
sizescale = sizescale or (lambda array: (np.array(array) - np.min(array)) / np.ptp(array) * 30)
size = sizescale(size)
marker = dict(
opacity = kwargs.get('marker_opacity', 0.5),
size = size,
showscale = False,
line = dict(
width = kwargs.get('marker_line_width', 1),
color = kwargs.get('marker_line_color', 'rgb(0,0,0)')
)
)
if color is not None:
if not isinstance(color, str):
if isinstance(colorscale, str):
colorscale = make_colorscale(colorscale, reverse=kwargs.get('colorscale_reverse', False))
marker['colorscale'] = colorscale
marker['showscale'] = kwargs.get('showscale', True)
marker['color'] = color
# make trace
trace = go.Splom(
dimensions=[{'label': name, 'values': data} for name, data in zip(names, datasets)],
marker=marker,
diagonal={'visible': False}
)
traces = [trace]
# add histogram
for i, (name, data, hist_layout) in enumerate(zip(names, datasets, hist_unique_layouts)):
start = np.min(data)
end = np.max(data)
bin_size = np.ptp(data) / kwargs.get('bin_num', 10)
trace = go.Histogram(
x=data, xbins=dict(start=start, end=end, size=bin_size),
name=name, autobinx=False,
xaxis='x{}'.format(i+ndata+1),
yaxis='y{}'.format(i+ndata+1,
**hist_layout, **hist_common_layout)
)
traces.append(trace)
hist_pos = kwargs.get('hist_pos', 0.15)
layout.update({
'xaxis{}'.format(i+ndata+1): {'domain': [1-(i+1)/ndata+hist_pos/ndata, 1-i/ndata-hist_pos/ndata], 'anchor': 'x{}'.format(i+ndata+1)}
for i in range(ndata)})
layout.update({
'yaxis{}'.format(i+ndata+1): {'domain': [i/ndata+hist_pos/ndata, (i+1)/ndata-hist_pos/ndata], 'anchor': 'y{}'.format(i+ndata+1)}
for i in range(ndata)})
layout.update(dict(
dragmode=kwargs.get('dragmode', 'select'),
hovermode='closest',
plot_bgcolor=kwargs.get('plot_bgcolor', None),
showlegend=False
))
fig = go.Figure(data=traces, layout=layout)
kwargs.get('save', False) and plty.plot(fig, filename=title+'.html', image_width=width, image_height=height, auto_open=False)
if kwargs.get('return_fig', False):
return fig
else:
plty.iplot(fig)
def plotly_clusters(
x,
y,
label,
names: dict = None,
sizes=6,
colorscale: Union[str, list] = '12,qual,Paired',
title: str = '2D Clusters',
**kwargs) -> None:
'''Docstring of `plotly_clusters`
Plot 2D clusters with plotly.
Args:
x: x axis.
y: y axis.
label: Label of data for clustering.
`x`, `y` and `label` must have same length.
names: Lables' names. Optional.
sizes: A single number or a number list.
Marker sizes of each cluster.
colorscale: Colors of clusters.
A list of `[percentage, color]` pairs, or a string
that can be passed to `make_colorscale`.
title: Title of the plot.
'''
assert len(x) == len(y) == len(label), 'Given data have different length. `x`:{}, `y`:{}, `label`:{}'.format(len(x), len(y), len(label))
width = kwargs.get('width', 900)
height = kwargs.get('height', 700)
layout = go.Layout(title=title, width=width, height=height, hovermode='closest')
layout.update(kwargs.get('layout', {}))
# group by labels
labels = np.unique(label)
datasets = np.c_[x, y, label]
if names is not None:
datasets = {names[k]: datasets[datasets[:,2]==k] for k in labels}
labels = [names[k] for k in labels]
else:
datasets = {k: datasets[datasets[:,2]==k] for k in labels}
n_labels = len(labels)
# check for size and colors
if isinstance(sizes, (int, float)):
sizes = [sizes]*n_labels
if isinstance(colorscale, str):
colorscale = [c[1] for c in make_colorscale(colorscale, n=n_labels, reverse=kwargs.get('colorscale_reverse', False))]
active_opacity = kwargs.get('active_opacity', 1)
active_line_width = kwargs.get('active_line_width', 1)
inactive_opacity = kwargs.get('inactive_opacity', 0.05)
inactive_line_width = kwargs.get('inactive_line_width', 0.1)
# buttons for selecting cluster to highlight
buttons = [dict(
label = 'Reset',
method = 'restyle',
args = [{
'marker.opacity': [active_opacity] * n_labels,
'marker.line.width': [active_line_width]*n_labels
}]
)]
# add data points cluster by cluster
traces = []
for i, (label, size, color) in enumerate(zip(labels, sizes, colorscale)):
data = datasets[label]
trace = go.Scattergl(
x=data[:,0], y=data[:,1], mode='markers', name=label,
marker=dict(color=color, size=size, opacity=active_opacity, line=dict(width=active_line_width)))
traces.append(trace)
button = dict(
label = 'Cluster {}'.format(label),
method = 'restyle',
args = [{
'marker.opacity': [inactive_opacity]*i + [active_opacity] + [inactive_opacity]*(n_labels-i-1),
'marker.line.width': [inactive_line_width]*i + [active_line_width] + [inactive_line_width]*(n_labels-i-1),
}]
)
buttons.append(button)
updatemenus = [
dict(
type='buttons',
buttons=buttons
)
]
layout.updatemenus = updatemenus
fig = go.Figure(data=traces, layout=layout)
kwargs.get('save', False) and plty.plot(fig, filename=title+'.html', image_width=width, image_height=height, auto_open=False)
if kwargs.get('return_fig', False):
return fig
else:
plty.iplot(fig)
def plotly_qq_plots(
datasets: Union[list, np.array],
names: Optional[Iterable[str]] = None,
ncols: Optional[int] = None,
title: str = 'QQ plots',
**kwargs) -> None:
'''Docstring of `plotly_qq_plots`
Plot QQ-plots of all the given data with plotly.
Args:
datasets: A list of data to plot.
names: Data names corresponding to items in data. Optional.
ncols: Number of subplots of every row.
Ignored when `subplots` is `False`.
If `None`, it's determined with `datasets`'s length.