forked from plotly/plotly.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_scatterplot.py
1136 lines (1018 loc) · 45.4 KB
/
_scatterplot.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 __future__ import absolute_import
from plotly import colors, exceptions, optional_imports
from plotly.figure_factory import utils
from plotly.graph_objs import graph_objs
from plotly.tools import make_subplots
pd = optional_imports.get_module('pandas')
DIAG_CHOICES = ['scatter', 'histogram', 'box']
VALID_COLORMAP_TYPES = ['cat', 'seq']
def endpts_to_intervals(endpts):
"""
Returns a list of intervals for categorical colormaps
Accepts a list or tuple of sequentially increasing numbers and returns
a list representation of the mathematical intervals with these numbers
as endpoints. For example, [1, 6] returns [[-inf, 1], [1, 6], [6, inf]]
:raises: (PlotlyError) If input is not a list or tuple
:raises: (PlotlyError) If the input contains a string
:raises: (PlotlyError) If any number does not increase after the
previous one in the sequence
"""
length = len(endpts)
# Check if endpts is a list or tuple
if not (isinstance(endpts, (tuple)) or isinstance(endpts, (list))):
raise exceptions.PlotlyError("The intervals_endpts argument must "
"be a list or tuple of a sequence "
"of increasing numbers.")
# Check if endpts contains only numbers
for item in endpts:
if isinstance(item, str):
raise exceptions.PlotlyError("The intervals_endpts argument "
"must be a list or tuple of a "
"sequence of increasing "
"numbers.")
# Check if numbers in endpts are increasing
for k in range(length - 1):
if endpts[k] >= endpts[k + 1]:
raise exceptions.PlotlyError("The intervals_endpts argument "
"must be a list or tuple of a "
"sequence of increasing "
"numbers.")
else:
intervals = []
# add -inf to intervals
intervals.append([float('-inf'), endpts[0]])
for k in range(length - 1):
interval = []
interval.append(endpts[k])
interval.append(endpts[k + 1])
intervals.append(interval)
# add +inf to intervals
intervals.append([endpts[length - 1], float('inf')])
return intervals
def hide_tick_labels_from_box_subplots(fig):
"""
Hides tick labels for box plots in scatterplotmatrix subplots.
"""
boxplot_xaxes = []
for trace in fig['data']:
if trace['type'] == 'box':
# stores the xaxes which correspond to boxplot subplots
# since we use xaxis1, xaxis2, etc, in plotly.py
boxplot_xaxes.append(
'xaxis{}'.format(trace['xaxis'][1:])
)
for xaxis in boxplot_xaxes:
fig['layout'][xaxis]['showticklabels'] = False
def validate_scatterplotmatrix(df, index, diag, colormap_type, **kwargs):
"""
Validates basic inputs for FigureFactory.create_scatterplotmatrix()
:raises: (PlotlyError) If pandas is not imported
:raises: (PlotlyError) If pandas dataframe is not inputted
:raises: (PlotlyError) If pandas dataframe has <= 1 columns
:raises: (PlotlyError) If diagonal plot choice (diag) is not one of
the viable options
:raises: (PlotlyError) If colormap_type is not a valid choice
:raises: (PlotlyError) If kwargs contains 'size', 'color' or
'colorscale'
"""
if not pd:
raise ImportError("FigureFactory.scatterplotmatrix requires "
"a pandas DataFrame.")
# Check if pandas dataframe
if not isinstance(df, pd.core.frame.DataFrame):
raise exceptions.PlotlyError("Dataframe not inputed. Please "
"use a pandas dataframe to pro"
"duce a scatterplot matrix.")
# Check if dataframe is 1 column or less
if len(df.columns) <= 1:
raise exceptions.PlotlyError("Dataframe has only one column. To "
"use the scatterplot matrix, use at "
"least 2 columns.")
# Check that diag parameter is a valid selection
if diag not in DIAG_CHOICES:
raise exceptions.PlotlyError("Make sure diag is set to "
"one of {}".format(DIAG_CHOICES))
# Check that colormap_types is a valid selection
if colormap_type not in VALID_COLORMAP_TYPES:
raise exceptions.PlotlyError("Must choose a valid colormap type. "
"Either 'cat' or 'seq' for a cate"
"gorical and sequential colormap "
"respectively.")
# Check for not 'size' or 'color' in 'marker' of **kwargs
if 'marker' in kwargs:
FORBIDDEN_PARAMS = ['size', 'color', 'colorscale']
if any(param in kwargs['marker'] for param in FORBIDDEN_PARAMS):
raise exceptions.PlotlyError("Your kwargs dictionary cannot "
"include the 'size', 'color' or "
"'colorscale' key words inside "
"the marker dict since 'size' is "
"already an argument of the "
"scatterplot matrix function and "
"both 'color' and 'colorscale "
"are set internally.")
def scatterplot(dataframe, headers, diag, size, height, width, title,
**kwargs):
"""
Refer to FigureFactory.create_scatterplotmatrix() for docstring
Returns fig for scatterplotmatrix without index
"""
dim = len(dataframe)
fig = make_subplots(rows=dim, cols=dim, print_grid=False)
trace_list = []
# Insert traces into trace_list
for listy in dataframe:
for listx in dataframe:
if (listx == listy) and (diag == 'histogram'):
trace = graph_objs.Histogram(
x=listx,
showlegend=False
)
elif (listx == listy) and (diag == 'box'):
trace = graph_objs.Box(
y=listx,
name=None,
showlegend=False
)
else:
if 'marker' in kwargs:
kwargs['marker']['size'] = size
trace = graph_objs.Scatter(
x=listx,
y=listy,
mode='markers',
showlegend=False,
**kwargs
)
trace_list.append(trace)
else:
trace = graph_objs.Scatter(
x=listx,
y=listy,
mode='markers',
marker=dict(
size=size),
showlegend=False,
**kwargs
)
trace_list.append(trace)
trace_index = 0
indices = range(1, dim + 1)
for y_index in indices:
for x_index in indices:
fig.append_trace(trace_list[trace_index],
y_index,
x_index)
trace_index += 1
# Insert headers into the figure
for j in range(dim):
xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j)
fig['layout'][xaxis_key].update(title=headers[j])
for j in range(dim):
yaxis_key = 'yaxis{}'.format(1 + (dim * j))
fig['layout'][yaxis_key].update(title=headers[j])
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True
)
hide_tick_labels_from_box_subplots(fig)
return fig
def scatterplot_dict(dataframe, headers, diag, size,
height, width, title, index, index_vals,
endpts, colormap, colormap_type, **kwargs):
"""
Refer to FigureFactory.create_scatterplotmatrix() for docstring
Returns fig for scatterplotmatrix with both index and colormap picked.
Used if colormap is a dictionary with index values as keys pointing to
colors. Forces colormap_type to behave categorically because it would
not make sense colors are assigned to each index value and thus
implies that a categorical approach should be taken
"""
theme = colormap
dim = len(dataframe)
fig = make_subplots(rows=dim, cols=dim, print_grid=False)
trace_list = []
legend_param = 0
# Work over all permutations of list pairs
for listy in dataframe:
for listx in dataframe:
# create a dictionary for index_vals
unique_index_vals = {}
for name in index_vals:
if name not in unique_index_vals:
unique_index_vals[name] = []
# Fill all the rest of the names into the dictionary
for name in sorted(unique_index_vals.keys()):
new_listx = []
new_listy = []
for j in range(len(index_vals)):
if index_vals[j] == name:
new_listx.append(listx[j])
new_listy.append(listy[j])
# Generate trace with VISIBLE icon
if legend_param == 1:
if (listx == listy) and (diag == 'histogram'):
trace = graph_objs.Histogram(
x=new_listx,
marker=dict(
color=theme[name]),
showlegend=True
)
elif (listx == listy) and (diag == 'box'):
trace = graph_objs.Box(
y=new_listx,
name=None,
marker=dict(
color=theme[name]),
showlegend=True
)
else:
if 'marker' in kwargs:
kwargs['marker']['size'] = size
kwargs['marker']['color'] = theme[name]
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=name,
showlegend=True,
**kwargs
)
else:
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=name,
marker=dict(
size=size,
color=theme[name]),
showlegend=True,
**kwargs
)
# Generate trace with INVISIBLE icon
else:
if (listx == listy) and (diag == 'histogram'):
trace = graph_objs.Histogram(
x=new_listx,
marker=dict(
color=theme[name]),
showlegend=False
)
elif (listx == listy) and (diag == 'box'):
trace = graph_objs.Box(
y=new_listx,
name=None,
marker=dict(
color=theme[name]),
showlegend=False
)
else:
if 'marker' in kwargs:
kwargs['marker']['size'] = size
kwargs['marker']['color'] = theme[name]
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=name,
showlegend=False,
**kwargs
)
else:
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=name,
marker=dict(
size=size,
color=theme[name]),
showlegend=False,
**kwargs
)
# Push the trace into dictionary
unique_index_vals[name] = trace
trace_list.append(unique_index_vals)
legend_param += 1
trace_index = 0
indices = range(1, dim + 1)
for y_index in indices:
for x_index in indices:
for name in sorted(trace_list[trace_index].keys()):
fig.append_trace(
trace_list[trace_index][name],
y_index,
x_index)
trace_index += 1
# Insert headers into the figure
for j in range(dim):
xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j)
fig['layout'][xaxis_key].update(title=headers[j])
for j in range(dim):
yaxis_key = 'yaxis{}'.format(1 + (dim * j))
fig['layout'][yaxis_key].update(title=headers[j])
hide_tick_labels_from_box_subplots(fig)
if diag == 'histogram':
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True,
barmode='stack')
return fig
else:
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True)
return fig
def scatterplot_theme(dataframe, headers, diag, size, height, width, title,
index, index_vals, endpts, colormap, colormap_type,
**kwargs):
"""
Refer to FigureFactory.create_scatterplotmatrix() for docstring
Returns fig for scatterplotmatrix with both index and colormap picked
"""
# Check if index is made of string values
if isinstance(index_vals[0], str):
unique_index_vals = []
for name in index_vals:
if name not in unique_index_vals:
unique_index_vals.append(name)
n_colors_len = len(unique_index_vals)
# Convert colormap to list of n RGB tuples
if colormap_type == 'seq':
foo = colors.color_parser(colormap, colors.unlabel_rgb)
foo = utils.n_colors(foo[0], foo[1], n_colors_len)
theme = colors.color_parser(foo, colors.label_rgb)
if colormap_type == 'cat':
# leave list of colors the same way
theme = colormap
dim = len(dataframe)
fig = make_subplots(rows=dim, cols=dim, print_grid=False)
trace_list = []
legend_param = 0
# Work over all permutations of list pairs
for listy in dataframe:
for listx in dataframe:
# create a dictionary for index_vals
unique_index_vals = {}
for name in index_vals:
if name not in unique_index_vals:
unique_index_vals[name] = []
c_indx = 0 # color index
# Fill all the rest of the names into the dictionary
for name in sorted(unique_index_vals.keys()):
new_listx = []
new_listy = []
for j in range(len(index_vals)):
if index_vals[j] == name:
new_listx.append(listx[j])
new_listy.append(listy[j])
# Generate trace with VISIBLE icon
if legend_param == 1:
if (listx == listy) and (diag == 'histogram'):
trace = graph_objs.Histogram(
x=new_listx,
marker=dict(
color=theme[c_indx]),
showlegend=True
)
elif (listx == listy) and (diag == 'box'):
trace = graph_objs.Box(
y=new_listx,
name=None,
marker=dict(
color=theme[c_indx]),
showlegend=True
)
else:
if 'marker' in kwargs:
kwargs['marker']['size'] = size
kwargs['marker']['color'] = theme[c_indx]
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=name,
showlegend=True,
**kwargs
)
else:
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=name,
marker=dict(
size=size,
color=theme[c_indx]),
showlegend=True,
**kwargs
)
# Generate trace with INVISIBLE icon
else:
if (listx == listy) and (diag == 'histogram'):
trace = graph_objs.Histogram(
x=new_listx,
marker=dict(
color=theme[c_indx]),
showlegend=False
)
elif (listx == listy) and (diag == 'box'):
trace = graph_objs.Box(
y=new_listx,
name=None,
marker=dict(
color=theme[c_indx]),
showlegend=False
)
else:
if 'marker' in kwargs:
kwargs['marker']['size'] = size
kwargs['marker']['color'] = theme[c_indx]
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=name,
showlegend=False,
**kwargs
)
else:
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=name,
marker=dict(
size=size,
color=theme[c_indx]),
showlegend=False,
**kwargs
)
# Push the trace into dictionary
unique_index_vals[name] = trace
if c_indx >= (len(theme) - 1):
c_indx = -1
c_indx += 1
trace_list.append(unique_index_vals)
legend_param += 1
trace_index = 0
indices = range(1, dim + 1)
for y_index in indices:
for x_index in indices:
for name in sorted(trace_list[trace_index].keys()):
fig.append_trace(
trace_list[trace_index][name],
y_index,
x_index)
trace_index += 1
# Insert headers into the figure
for j in range(dim):
xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j)
fig['layout'][xaxis_key].update(title=headers[j])
for j in range(dim):
yaxis_key = 'yaxis{}'.format(1 + (dim * j))
fig['layout'][yaxis_key].update(title=headers[j])
hide_tick_labels_from_box_subplots(fig)
if diag == 'histogram':
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True,
barmode='stack')
return fig
elif diag == 'box':
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True)
return fig
else:
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True)
return fig
else:
if endpts:
intervals = utils.endpts_to_intervals(endpts)
# Convert colormap to list of n RGB tuples
if colormap_type == 'seq':
foo = colors.color_parser(colormap, colors.unlabel_rgb)
foo = utils.n_colors(foo[0], foo[1], len(intervals))
theme = colors.color_parser(foo, colors.label_rgb)
if colormap_type == 'cat':
# leave list of colors the same way
theme = colormap
dim = len(dataframe)
fig = make_subplots(rows=dim, cols=dim, print_grid=False)
trace_list = []
legend_param = 0
# Work over all permutations of list pairs
for listy in dataframe:
for listx in dataframe:
interval_labels = {}
for interval in intervals:
interval_labels[str(interval)] = []
c_indx = 0 # color index
# Fill all the rest of the names into the dictionary
for interval in intervals:
new_listx = []
new_listy = []
for j in range(len(index_vals)):
if interval[0] < index_vals[j] <= interval[1]:
new_listx.append(listx[j])
new_listy.append(listy[j])
# Generate trace with VISIBLE icon
if legend_param == 1:
if (listx == listy) and (diag == 'histogram'):
trace = graph_objs.Histogram(
x=new_listx,
marker=dict(
color=theme[c_indx]),
showlegend=True
)
elif (listx == listy) and (diag == 'box'):
trace = graph_objs.Box(
y=new_listx,
name=None,
marker=dict(
color=theme[c_indx]),
showlegend=True
)
else:
if 'marker' in kwargs:
kwargs['marker']['size'] = size
(kwargs['marker']
['color']) = theme[c_indx]
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=str(interval),
showlegend=True,
**kwargs
)
else:
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=str(interval),
marker=dict(
size=size,
color=theme[c_indx]),
showlegend=True,
**kwargs
)
# Generate trace with INVISIBLE icon
else:
if (listx == listy) and (diag == 'histogram'):
trace = graph_objs.Histogram(
x=new_listx,
marker=dict(
color=theme[c_indx]),
showlegend=False
)
elif (listx == listy) and (diag == 'box'):
trace = graph_objs.Box(
y=new_listx,
name=None,
marker=dict(
color=theme[c_indx]),
showlegend=False
)
else:
if 'marker' in kwargs:
kwargs['marker']['size'] = size
(kwargs['marker']
['color']) = theme[c_indx]
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=str(interval),
showlegend=False,
**kwargs
)
else:
trace = graph_objs.Scatter(
x=new_listx,
y=new_listy,
mode='markers',
name=str(interval),
marker=dict(
size=size,
color=theme[c_indx]),
showlegend=False,
**kwargs
)
# Push the trace into dictionary
interval_labels[str(interval)] = trace
if c_indx >= (len(theme) - 1):
c_indx = -1
c_indx += 1
trace_list.append(interval_labels)
legend_param += 1
trace_index = 0
indices = range(1, dim + 1)
for y_index in indices:
for x_index in indices:
for interval in intervals:
fig.append_trace(
trace_list[trace_index][str(interval)],
y_index,
x_index)
trace_index += 1
# Insert headers into the figure
for j in range(dim):
xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j)
fig['layout'][xaxis_key].update(title=headers[j])
for j in range(dim):
yaxis_key = 'yaxis{}'.format(1 + (dim * j))
fig['layout'][yaxis_key].update(title=headers[j])
hide_tick_labels_from_box_subplots(fig)
if diag == 'histogram':
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True,
barmode='stack')
return fig
elif diag == 'box':
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True)
return fig
else:
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True)
return fig
else:
theme = colormap
# add a copy of rgb color to theme if it contains one color
if len(theme) <= 1:
theme.append(theme[0])
color = []
for incr in range(len(theme)):
color.append([1. / (len(theme) - 1) * incr, theme[incr]])
dim = len(dataframe)
fig = make_subplots(rows=dim, cols=dim, print_grid=False)
trace_list = []
legend_param = 0
# Run through all permutations of list pairs
for listy in dataframe:
for listx in dataframe:
# Generate trace with VISIBLE icon
if legend_param == 1:
if (listx == listy) and (diag == 'histogram'):
trace = graph_objs.Histogram(
x=listx,
marker=dict(
color=theme[0]),
showlegend=False
)
elif (listx == listy) and (diag == 'box'):
trace = graph_objs.Box(
y=listx,
marker=dict(
color=theme[0]),
showlegend=False
)
else:
if 'marker' in kwargs:
kwargs['marker']['size'] = size
kwargs['marker']['color'] = index_vals
kwargs['marker']['colorscale'] = color
kwargs['marker']['showscale'] = True
trace = graph_objs.Scatter(
x=listx,
y=listy,
mode='markers',
showlegend=False,
**kwargs
)
else:
trace = graph_objs.Scatter(
x=listx,
y=listy,
mode='markers',
marker=dict(
size=size,
color=index_vals,
colorscale=color,
showscale=True),
showlegend=False,
**kwargs
)
# Generate trace with INVISIBLE icon
else:
if (listx == listy) and (diag == 'histogram'):
trace = graph_objs.Histogram(
x=listx,
marker=dict(
color=theme[0]),
showlegend=False
)
elif (listx == listy) and (diag == 'box'):
trace = graph_objs.Box(
y=listx,
marker=dict(
color=theme[0]),
showlegend=False
)
else:
if 'marker' in kwargs:
kwargs['marker']['size'] = size
kwargs['marker']['color'] = index_vals
kwargs['marker']['colorscale'] = color
kwargs['marker']['showscale'] = False
trace = graph_objs.Scatter(
x=listx,
y=listy,
mode='markers',
showlegend=False,
**kwargs
)
else:
trace = graph_objs.Scatter(
x=listx,
y=listy,
mode='markers',
marker=dict(
size=size,
color=index_vals,
colorscale=color,
showscale=False),
showlegend=False,
**kwargs
)
# Push the trace into list
trace_list.append(trace)
legend_param += 1
trace_index = 0
indices = range(1, dim + 1)
for y_index in indices:
for x_index in indices:
fig.append_trace(trace_list[trace_index],
y_index,
x_index)
trace_index += 1
# Insert headers into the figure
for j in range(dim):
xaxis_key = 'xaxis{}'.format((dim * dim) - dim + 1 + j)
fig['layout'][xaxis_key].update(title=headers[j])
for j in range(dim):
yaxis_key = 'yaxis{}'.format(1 + (dim * j))
fig['layout'][yaxis_key].update(title=headers[j])
hide_tick_labels_from_box_subplots(fig)
if diag == 'histogram':
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True,
barmode='stack')
return fig
elif diag == 'box':
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True)
return fig
else:
fig['layout'].update(
height=height, width=width,
title=title,
showlegend=True)
return fig
def create_scatterplotmatrix(df, index=None, endpts=None, diag='scatter',
height=500, width=500, size=6,
title='Scatterplot Matrix', colormap=None,
colormap_type='cat', dataframe=None,
headers=None, index_vals=None, **kwargs):
"""
Returns data for a scatterplot matrix.
:param (array) df: array of the data with column headers
:param (str) index: name of the index column in data array
:param (list|tuple) endpts: takes an increasing sequece of numbers
that defines intervals on the real line. They are used to group
the entries in an index of numbers into their corresponding
interval and therefore can be treated as categorical data
:param (str) diag: sets the chart type for the main diagonal plots.
The options are 'scatter', 'histogram' and 'box'.
:param (int|float) height: sets the height of the chart
:param (int|float) width: sets the width of the chart
:param (float) size: sets the marker size (in px)
:param (str) title: the title label of the scatterplot matrix
:param (str|tuple|list|dict) colormap: either a plotly scale name,
an rgb or hex color, a color tuple, a list of colors or a
dictionary. An rgb color is of the form 'rgb(x, y, z)' where
x, y and z belong to the interval [0, 255] and a color tuple is a
tuple of the form (a, b, c) where a, b and c belong to [0, 1].
If colormap is a list, it must contain valid color types as its
members.
If colormap is a dictionary, all the string entries in
the index column must be a key in colormap. In this case, the
colormap_type is forced to 'cat' or categorical
:param (str) colormap_type: determines how colormap is interpreted.
Valid choices are 'seq' (sequential) and 'cat' (categorical). If
'seq' is selected, only the first two colors in colormap will be
considered (when colormap is a list) and the index values will be
linearly interpolated between those two colors. This option is
forced if all index values are numeric.
If 'cat' is selected, a color from colormap will be assigned to
each category from index, including the intervals if endpts is
being used
:param (dict) **kwargs: a dictionary of scatterplot arguments
The only forbidden parameters are 'size', 'color' and
'colorscale' in 'marker'
Example 1: Vanilla Scatterplot Matrix
```
import plotly.plotly as py
from plotly.graph_objs import graph_objs
from plotly.figure_factory import create_scatterplotmatrix
import numpy as np
import pandas as pd
# Create dataframe
df = pd.DataFrame(np.random.randn(10, 2),
columns=['Column 1', 'Column 2'])
# Create scatterplot matrix
fig = create_scatterplotmatrix(df)
# Plot
py.iplot(fig, filename='Vanilla Scatterplot Matrix')
```
Example 2: Indexing a Column
```
import plotly.plotly as py
from plotly.graph_objs import graph_objs
from plotly.figure_factory import create_scatterplotmatrix
import numpy as np
import pandas as pd
# Create dataframe with index
df = pd.DataFrame(np.random.randn(10, 2),
columns=['A', 'B'])
# Add another column of strings to the dataframe
df['Fruit'] = pd.Series(['apple', 'apple', 'grape', 'apple', 'apple',
'grape', 'pear', 'pear', 'apple', 'pear'])
# Create scatterplot matrix
fig = create_scatterplotmatrix(df, index='Fruit', size=10)
# Plot
py.iplot(fig, filename = 'Scatterplot Matrix with Index')
```
Example 3: Styling the Diagonal Subplots
```
import plotly.plotly as py
from plotly.graph_objs import graph_objs
from plotly.figure_factory import create_scatterplotmatrix
import numpy as np
import pandas as pd
# Create dataframe with index
df = pd.DataFrame(np.random.randn(10, 4),
columns=['A', 'B', 'C', 'D'])
# Add another column of strings to the dataframe
df['Fruit'] = pd.Series(['apple', 'apple', 'grape', 'apple', 'apple',
'grape', 'pear', 'pear', 'apple', 'pear'])
# Create scatterplot matrix
fig = create_scatterplotmatrix(df, diag='box', index='Fruit', height=1000,
width=1000)
# Plot
py.iplot(fig, filename = 'Scatterplot Matrix - Diagonal Styling')
```
Example 4: Use a Theme to Style the Subplots
```
import plotly.plotly as py
from plotly.graph_objs import graph_objs
from plotly.figure_factory import create_scatterplotmatrix
import numpy as np
import pandas as pd
# Create dataframe with random data
df = pd.DataFrame(np.random.randn(100, 3),
columns=['A', 'B', 'C'])
# Create scatterplot matrix using a built-in
# Plotly palette scale and indexing column 'A'
fig = create_scatterplotmatrix(df, diag='histogram', index='A',
colormap='Blues', height=800, width=800)
# Plot