-
Notifications
You must be signed in to change notification settings - Fork 463
/
pyplot.py
1335 lines (1112 loc) · 45.5 KB
/
pyplot.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
# Copyright 2015 Bloomberg Finance L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from collections import OrderedDict
from IPython.display import display
from ipywidgets import Image as ipyImage
from numpy import arange, issubdtype, array, column_stack, shape
from .figure import Figure
from bqscales import Scale, LinearScale, Mercator
from .axes import Axis
from .marks import (Lines, Scatter, Hist, Bars, OHLC, Pie, Map, Image,
Label, HeatMap, GridHeatMap, topo_load, Boxplot, Bins)
from .interacts import (BrushIntervalSelector, FastIntervalSelector,
BrushSelector, IndexSelector, MultiSelector,
LassoSelector)
from traitlets.utils.sentinel import Sentinel
import functools
Keep = Sentinel('Keep', 'bqplot.pyplot', '''
Used in bqplot.pyplot to specify that the same scale should be used for
a certain dimension.
''')
# `_context` object contains the global information for pyplot.
# `figure`: refers to the current figure to which marks will be added.
# `scales`: The current set of scales which will be used for drawing a mark. if
# the scale for an attribute is not present, it is created based on the range
# type.
# `scale_registry`: This is a dictionary where the keys are the context
# names and the values are the set of scales which were used on the last plot
# in that context. This is useful when switching context.
# `last_mark`: refers to the last mark that has been plotted.
# `current_key`: The key for the current context figure. If there is no key,
# then the value is `None`.
_context = {
'figure': None,
'figure_registry': {},
'scales': {},
'scale_registry': {},
'last_mark': None,
'current_key': None
}
LINE_STYLE_CODES = OrderedDict([(':', 'dotted'), ('-.', 'dash_dotted'),
('--', 'dashed'), ('-', 'solid')])
COLOR_CODES = {'b': 'blue', 'g': 'green', 'r': 'red', 'c': 'cyan',
'm': 'magenta', 'y': 'yellow', 'k': 'black'}
MARKER_CODES = {'o': 'circle', 'v': 'triangle-down', '^': 'triangle-up',
's': 'square', 'd': 'diamond', '+': 'cross', 'p': 'plus',
'x': 'crosshair', '.': 'point'}
PY2 = sys.version_info[0] == 2
if PY2:
string_types = basestring, # noqa
else:
string_types = str,
# Determine whether `v` can be hashed.
def hashable(data, v):
try:
data[v]
except (TypeError, KeyError, IndexError):
return False
return True
def show(key=None, display_toolbar=True):
"""Shows the current context figure in the output area.
Parameters
----------
key : hashable, optional
Any variable that can be used as a key for a dictionary.
display_toolbar: bool (default: True)
If True, a toolbar for different mouse interaction is displayed with
the figure.
Raises
------
KeyError
When no context figure is associated with the provided key.
Examples
--------
>>> import numpy as np
>>> import pyplot as plt
>>> n = 100
>>> x = np.arange(n)
>>> y = np.cumsum(np.random.randn(n))
>>> plt.plot(x,y)
>>> plt.show()
"""
if key is None:
figure = current_figure()
else:
figure = _context['figure_registry'][key]
figure.display_toolbar = display_toolbar
display(figure)
def figure(key=None, fig=None, **kwargs):
"""Creates figures and switches between figures.
If a ``bqplot.Figure`` object is provided via the fig optional argument,
this figure becomes the current context figure.
Otherwise:
- If no key is provided, a new empty context figure is created.
- If a key is provided for which a context already exists, the
corresponding context becomes current.
- If a key is provided and no corresponding context exists, a new context
is reated for that key and becomes current.
Besides, optional arguments allow to set or modify Attributes
of the selected context figure.
Parameters
----------
key: hashable, optional
Any variable that can be used as a key for a dictionary
fig: Figure, optional
A bqplot Figure
"""
scales_arg = kwargs.pop('scales', {})
_context['current_key'] = key
if fig is not None: # fig provided
_context['figure'] = fig
if key is not None:
_context['figure_registry'][key] = fig
for arg in kwargs:
setattr(_context['figure'], arg, kwargs[arg])
else: # no fig provided
if key is None: # no key provided
_context['figure'] = Figure(**kwargs)
else: # a key is provided
if key not in _context['figure_registry']:
if 'title' not in kwargs:
kwargs['title'] = 'Figure' + ' ' + str(key)
_context['figure_registry'][key] = Figure(**kwargs)
_context['figure'] = _context['figure_registry'][key]
for arg in kwargs:
setattr(_context['figure'], arg, kwargs[arg])
scales(key, scales=scales_arg)
# Set the axis reference dictionary. This dictionary contains the mapping
# from the possible dimensions in the figure to the list of scales with
# respect to which axes have been drawn for this figure.
# Used to automatically generate axis.
if getattr(_context['figure'], 'axis_registry', None) is None:
setattr(_context['figure'], 'axis_registry', {})
return _context['figure']
def close(key):
"""Closes and unregister the context figure corresponding to the key.
Parameters
----------
key: hashable
Any variable that can be used as a key for a dictionary
"""
figure_registry = _context['figure_registry']
if key not in figure_registry:
return
if _context['figure'] == figure_registry[key]:
figure()
fig = figure_registry[key]
if hasattr(fig, 'pyplot'):
fig.pyplot.close()
fig.pyplot_vbox.close()
fig.close()
del figure_registry[key]
del _context['scale_registry'][key]
def _process_data(*kwarg_names):
"""Helper function to handle data keyword argument
"""
def _data_decorator(func):
@functools.wraps(func)
def _mark_with_data(*args, **kwargs):
data = kwargs.pop('data', None)
if data is None:
return func(*args, **kwargs)
else:
data_args = [data[i] if hashable(data, i) else i for i in args]
data_kwargs = {
kw: data[kwargs[kw]] if hashable(data, kwargs[kw]) else kwargs[kw] for kw in set(kwarg_names).intersection(list(kwargs.keys()))
}
try:
# if any of the plots want to use the index_data, they can
# use it by referring to this attribute.
data_kwargs['index_data'] = data.index
except AttributeError:
pass
kwargs_update = kwargs.copy()
kwargs_update.update(data_kwargs)
return func(*data_args, **kwargs_update)
return _mark_with_data
return _data_decorator
def scales(key=None, scales={}):
"""Creates and switches between context scales.
If no key is provided, a new blank context is created.
If a key is provided for which a context already exists, the existing
context is set as the current context.
If a key is provided and no corresponding context exists, a new context is
created for that key and set as the current context.
Parameters
----------
key: hashable, optional
Any variable that can be used as a key for a dictionary
scales: dictionary
Dictionary of scales to be used in the new context
Example
-------
>>> scales(scales={
>>> 'x': Keep,
>>> 'color': ColorScale(min=0, max=1)
>>> })
This creates a new scales context, where the 'x' scale is kept from the
previous context, the 'color' scale is an instance of ColorScale
provided by the user. Other scales, potentially needed such as the 'y'
scale in the case of a line chart will be created on the fly when
needed.
Notes
-----
Every call to the function figure triggers a call to scales.
The `scales` parameter is ignored if the `key` argument is not Keep and
context scales already exist for that key.
"""
old_ctxt = _context['scales']
if key is None: # No key provided
_context['scales'] = {_get_attribute_dimension(k): scales[k] if scales[k] is not Keep
else old_ctxt[_get_attribute_dimension(k)] for k in scales}
else: # A key is provided
if key not in _context['scale_registry']:
_context['scale_registry'][key] = {
_get_attribute_dimension(k): scales[k]
if scales[k] is not Keep
else old_ctxt[_get_attribute_dimension(k)]
for k in scales
}
_context['scales'] = _context['scale_registry'][key]
def xlim(min, max):
"""Set the domain bounds of the current 'x' scale.
"""
return set_lim(min, max, 'x')
def ylim(min, max):
"""Set the domain bounds of the current 'y' scale.
"""
return set_lim(min, max, 'y')
def set_lim(min, max, name):
"""Set the domain bounds of the scale associated with the provided key.
Parameters
----------
name: hashable
Any variable that can be used as a key for a dictionary
Raises
------
KeyError
When no context figure is associated with the provided key.
"""
scale = _context['scales'][_get_attribute_dimension(name)]
scale.min = min
scale.max = max
return scale
def axes(mark=None, options={}, **kwargs):
"""Draws axes corresponding to the scales of a given mark.
It also returns a dictionary of drawn axes. If the mark is not provided,
the last drawn mark is used.
Parameters
----------
mark: Mark or None (default: None)
The mark to inspect to create axes. If None, the last mark drawn is
used instead.
options: dict (default: {})
Options for the axes to be created. If a scale labeled 'x' is required
for that mark, options['x'] contains optional keyword arguments for the
constructor of the corresponding axis type.
"""
if mark is None:
mark = _context['last_mark']
if mark is None:
return {}
fig = kwargs.get('figure', current_figure())
scales = mark.scales
fig_axes = [axis for axis in fig.axes]
axes = {}
for name in scales:
if name not in mark.class_trait_names(scaled=True):
# The scale is not needed.
continue
scale_metadata = mark.scales_metadata.get(name, {})
dimension = scale_metadata.get('dimension', scales[name])
axis_args = dict(scale_metadata,
**(options.get(name, {})))
axis = _fetch_axis(fig, dimension, scales[name])
if axis is not None:
# For this figure, an axis exists for the scale in the given
# dimension. Apply the properties and return back the object.
_apply_properties(axis, options.get(name, {}))
axes[name] = axis
continue
# An axis must be created. We fetch the type from the registry
# the key being provided in the scaled attribute decoration
key = mark.class_traits()[name].get_metadata('atype')
if key is not None:
axis_type = Axis.axis_types[key]
axis = axis_type(scale=scales[name], **axis_args)
axes[name] = axis
fig_axes.append(axis)
# Update the axis registry of the figure once the axis is added
_update_fig_axis_registry(fig, dimension, scales[name], axis)
fig.axes = fig_axes
return axes
def _set_label(label, mark, dim, **kwargs):
"""Helper function to set labels for an axis
"""
if mark is None:
mark = _context['last_mark']
if mark is None:
return {}
fig = kwargs.get('figure', current_figure())
scales = mark.scales
scale_metadata = mark.scales_metadata.get(dim, {})
scale = scales.get(dim, None)
if scale is None:
return
dimension = scale_metadata.get('dimension', scales[dim])
axis = _fetch_axis(fig, dimension, scales[dim])
if axis is not None:
_apply_properties(axis, {'label': label})
def xlabel(label=None, mark=None, **kwargs):
"""Sets the value of label for an axis whose associated scale has the
dimension `x`.
Parameters
----------
label: Unicode or None (default: None)
The label for x axis
"""
_set_label(label, mark, 'x', **kwargs)
def ylabel(label=None, mark=None, **kwargs):
"""Sets the value of label for an axis whose associated scale has the
dimension `y`.
Parameters
----------
label: Unicode or None (default: None)
The label for y axis
"""
_set_label(label, mark, 'y', **kwargs)
def grids(fig=None, value='solid'):
"""Sets the value of the grid_lines for the axis to the passed value.
The default value is `solid`.
Parameters
----------
fig: Figure or None(default: None)
The figure for which the axes should be edited. If the value is None,
the current figure is used.
value: {'none', 'solid', 'dashed'}
The display of the grid_lines
"""
if fig is None:
fig = current_figure()
for a in fig.axes:
a.grid_lines = value
def title(label, style=None):
"""Sets the title for the current figure.
Parameters
----------
label : str
The new title for the current figure.
style: dict
The CSS style to be applied to the figure title
"""
fig = current_figure()
fig.title = label
if style is not None:
fig.title_style = style
def legend():
"""Places legend in the current figure."""
for m in current_figure().marks:
m.display_legend = True
def hline(level, **kwargs):
"""Draws a horizontal line at the given level.
Parameters
----------
level: float
The level at which to draw the horizontal line.
preserve_domain: boolean (default: False)
If true, the line does not affect the domain of the 'y' scale.
"""
kwargs.setdefault('colors', ['dodgerblue'])
kwargs.setdefault('stroke_width', 1)
scales = kwargs.pop('scales', {})
fig = kwargs.get('figure', current_figure())
scales['x'] = fig.scale_x
level = array(level)
if len(level.shape) == 0:
x = [0, 1]
y = [level, level]
else:
x = [0, 1]
y = column_stack([level, level])
return plot(x, y, scales=scales, preserve_domain={
'x': True,
'y': kwargs.get('preserve_domain', False)
}, axes=False, update_context=False, **kwargs)
def vline(level, **kwargs):
"""Draws a vertical line at the given level.
Parameters
----------
level: float
The level at which to draw the vertical line.
preserve_domain: boolean (default: False)
If true, the line does not affect the domain of the 'x' scale.
"""
kwargs.setdefault('colors', ['dodgerblue'])
kwargs.setdefault('stroke_width', 1)
scales = kwargs.pop('scales', {})
fig = kwargs.get('figure', current_figure())
scales['y'] = fig.scale_y
level = array(level)
if len(level.shape) == 0:
x = [level, level]
y = [0, 1]
else:
x = column_stack([level, level])
# TODO: repeating [0, 1] should not be required once we allow for
# 2-D x and 1-D y
y = [[0, 1]] * len(level)
return plot(x, y, scales=scales, preserve_domain={
'x': kwargs.get('preserve_domain', False),
'y': True
}, axes=False, update_context=False, **kwargs)
def _process_cmap(cmap):
'''
Returns a kwarg dict suitable for a ColorScale
'''
option = {}
if isinstance(cmap, str):
option['scheme'] = cmap
elif isinstance(cmap, list):
option['colors'] = cmap
else:
raise ValueError('''`cmap` must be a string (name of a color scheme)
or a list of colors, but a value of {} was given
'''.format(cmap))
return option
def set_cmap(cmap):
'''
Set the color map of the current 'color' scale.
'''
scale = _context['scales']['color']
for k, v in _process_cmap(cmap).items():
setattr(scale, k, v)
return scale
def _draw_mark(mark_type, options={}, axes_options={}, **kwargs):
"""Draw the mark of specified mark type.
Parameters
----------
mark_type: type
The type of mark to be drawn
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is required
for that mark, axes_options['x'] contains optional keyword arguments
for the constructor of the corresponding axis type.
figure: Figure or None
The figure to which the mark is to be added.
If the value is None, the current figure is used.
cmap: list or string
List of css colors, or name of bqplot color scheme
"""
fig = kwargs.pop('figure', current_figure())
scales = kwargs.pop('scales', {})
update_context = kwargs.pop('update_context', True)
# Set the color map of the color scale
cmap = kwargs.pop('cmap', None)
if cmap is not None:
# Add the colors or scheme to the color scale options
options['color'] = dict(options.get('color', {}),
**_process_cmap(cmap))
# Going through the list of data attributes
for name in mark_type.class_trait_names(scaled=True):
dimension = _get_attribute_dimension(name, mark_type)
# TODO: the following should also happen if name in kwargs and
# scales[name] is incompatible.
if name not in kwargs:
# The scaled attribute is not being passed to the mark. So no need
# create a scale for this.
continue
elif name in scales:
if update_context:
_context['scales'][dimension] = scales[name]
# Scale has to be fetched from the context or created as it has not
# been passed.
elif dimension not in _context['scales']:
# Creating a scale for the dimension if a matching scale is not
# present in _context['scales']
traitlet = mark_type.class_traits()[name]
rtype = traitlet.get_metadata('rtype')
dtype = traitlet.validate(None, kwargs[name]).dtype
# Fetching the first matching scale for the rtype and dtype of the
# scaled attributes of the mark.
compat_scale_types = [
Scale.scale_types[key]
for key in Scale.scale_types
if Scale.scale_types[key].rtype == rtype and issubdtype(dtype, Scale.scale_types[key].dtype)
]
sorted_scales = sorted(compat_scale_types,
key=lambda x: x.precedence)
scales[name] = sorted_scales[-1](**options.get(name, {}))
# Adding the scale to the context scales
if update_context:
_context['scales'][dimension] = scales[name]
else:
scales[name] = _context['scales'][dimension]
mark = mark_type(scales=scales, **kwargs)
_context['last_mark'] = mark
fig.marks = [m for m in fig.marks] + [mark]
if kwargs.get('axes', True):
axes(mark, options=axes_options)
return mark
def _infer_x_for_line(y):
"""
Infers the x for a line if no x is provided.
"""
array_shape = shape(y)
if len(array_shape) == 0:
return []
if len(array_shape) == 1:
return arange(array_shape[0])
if len(array_shape) > 1:
return arange(array_shape[1])
@_process_data('color')
def plot(*args, **kwargs):
"""Draw lines in the current context figure.
Signature: `plot(x, y, **kwargs)` or `plot(y, **kwargs)`, depending of the
length of the list of positional arguments. In the case where the `x` array
is not provided.
Parameters
----------
x: numpy.ndarray or list, 1d or 2d (optional)
The x-coordinates of the plotted line. When not provided, the function
defaults to `numpy.arange(len(y))`
x can be 1-dimensional or 2-dimensional.
y: numpy.ndarray or list, 1d or 2d
The y-coordinates of the plotted line. If argument `x` is 2-dimensional
it must also be 2-dimensional.
marker_str: string
string representing line_style, marker and color.
For e.g. 'g--o', 'sr' etc
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is required
for that mark, axes_options['x'] contains optional keyword arguments
for the constructor of the corresponding axis type.
figure: Figure or None
The figure to which the line is to be added.
If the value is None, the current figure is used.
"""
marker_str = None
if len(args) == 1:
kwargs['y'] = args[0]
if kwargs.get('index_data', None) is not None:
kwargs['x'] = kwargs['index_data']
else:
kwargs['x'] = _infer_x_for_line(args[0])
elif len(args) == 2:
if isinstance(args[1], str):
kwargs['y'] = args[0]
kwargs['x'] = _infer_x_for_line(args[0])
marker_str = args[1].strip()
else:
kwargs['x'] = args[0]
kwargs['y'] = args[1]
elif len(args) == 3:
kwargs['x'] = args[0]
kwargs['y'] = args[1]
if isinstance(args[2], str):
marker_str = args[2].strip()
if marker_str:
line_style, color, marker = _get_line_styles(marker_str)
# only marker specified => draw scatter
if marker and not line_style:
kwargs['marker'] = marker
if color:
kwargs['colors'] = [color]
return _draw_mark(Scatter, **kwargs)
else: # draw lines in all other cases
kwargs['line_style'] = line_style or 'solid'
if marker:
kwargs['marker'] = marker
if color:
kwargs['colors'] = [color]
return _draw_mark(Lines, **kwargs)
else:
return _draw_mark(Lines, **kwargs)
def imshow(image, format, **kwargs):
"""Draw an image in the current context figure.
Parameters
----------
image: image data
Image data, depending on the passed format, can be one of:
- an instance of an ipywidgets Image
- a file name
- a raw byte string
format: {'widget', 'filename', ...}
Type of the input argument.
If not 'widget' or 'filename', must be a format supported by
the ipywidgets Image.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is required
for that mark, axes_options['x'] contains optional keyword arguments
for the constructor of the corresponding axis type.
"""
if format == 'widget':
ipyimage = image
elif format == 'filename':
with open(image, 'rb') as f:
data = f.read()
ipyimage = ipyImage(value=data)
else:
ipyimage = ipyImage(value=image, format=format)
kwargs['image'] = ipyimage
kwargs.setdefault('x', [0., 1.])
kwargs.setdefault('y', [0., 1.])
return _draw_mark(Image, **kwargs)
def ohlc(*args, **kwargs):
"""Draw OHLC bars or candle bars in the current context figure.
Signature: `ohlc(x, y, **kwargs)` or `ohlc(y, **kwargs)`, depending of the
length of the list of positional arguments. In the case where the `x` array
is not provided
Parameters
----------
x: numpy.ndarray or list, 1d (optional)
The x-coordinates of the plotted line. When not provided, the function
defaults to `numpy.arange(len(y))`.
y: numpy.ndarray or list, 2d
The ohlc (open/high/low/close) information. A two dimensional array. y
must have the shape (n, 4).
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is required
for that mark, axes_options['x'] contains optional keyword arguments
for the constructor of the corresponding axis type.
"""
if len(args) == 2:
kwargs['x'] = args[0]
kwargs['y'] = args[1]
elif len(args) == 1:
kwargs['y'] = args[0]
length = len(args[0])
kwargs['x'] = arange(length)
return _draw_mark(OHLC, **kwargs)
@_process_data('color', 'opacity', 'size', 'skew', 'rotation')
def scatter(x, y, **kwargs):
"""Draw a scatter in the current context figure.
Parameters
----------
x: numpy.ndarray, 1d
The x-coordinates of the data points.
y: numpy.ndarray, 1d
The y-coordinates of the data points.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is required
for that mark, axes_options['x'] contains optional keyword arguments
for the constructor of the corresponding axis type.
"""
kwargs['x'] = x
kwargs['y'] = y
return _draw_mark(Scatter, **kwargs)
@_process_data()
def hist(sample, options={}, **kwargs):
"""Draw a histogram in the current context figure.
Parameters
----------
sample: numpy.ndarray, 1d
The sample for which the histogram must be generated.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'counts'
is required for that mark, options['counts'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'counts' is
required for that mark, axes_options['counts'] contains optional
keyword arguments for the constructor of the corresponding axis type.
"""
kwargs['sample'] = sample
scales = kwargs.pop('scales', {})
if 'count' not in scales:
dimension = _get_attribute_dimension('count', Hist)
if dimension in _context['scales']:
scales['count'] = _context['scales'][dimension]
else:
scales['count'] = LinearScale(**options.get('count', {}))
_context['scales'][dimension] = scales['count']
kwargs['scales'] = scales
return _draw_mark(Hist, options=options, **kwargs)
@_process_data()
def bin(sample, options={}, **kwargs):
"""Draw a histogram in the current context figure.
Parameters
----------
sample: numpy.ndarray, 1d
The sample for which the histogram must be generated.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x'
is required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is
required for that mark, axes_options['x'] contains optional
keyword arguments for the constructor of the corresponding axis type.
"""
kwargs['sample'] = sample
scales = kwargs.pop('scales', {})
for xy in ['x', 'y']:
if xy not in scales:
dimension = _get_attribute_dimension(xy, Bars)
if dimension in _context['scales']:
scales[xy] = _context['scales'][dimension]
else:
scales[xy] = LinearScale(**options.get(xy, {}))
_context['scales'][dimension] = scales[xy]
kwargs['scales'] = scales
return _draw_mark(Bins, options=options, **kwargs)
@_process_data('color')
def bar(x, y, **kwargs):
"""Draws a bar chart in the current context figure.
Parameters
----------
x: numpy.ndarray, 1d
The x-coordinates of the data points.
y: numpy.ndarray, 1d
The y-coordinates of the data pints.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is required
for that mark, axes_options['x'] contains optional keyword arguments
for the constructor of the corresponding axis type.
"""
kwargs['x'] = x
kwargs['y'] = y
return _draw_mark(Bars, **kwargs)
@_process_data()
def boxplot(x, y, **kwargs):
"""Draws a boxplot in the current context figure.
Parameters
----------
x: numpy.ndarray, 1d
The x-coordinates of the data points.
y: numpy.ndarray, 2d
The data from which the boxes are to be created. Each row of the data
corresponds to one box drawn in the plot.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is required
for that mark, axes_options['x'] contains optional keyword arguments
for the constructor of the corresponding axis type.
"""
kwargs['x'] = x
kwargs['y'] = y
return _draw_mark(Boxplot, **kwargs)
@_process_data('color')
def barh(*args, **kwargs):
"""Draws a horizontal bar chart in the current context figure.
Parameters
----------
x: numpy.ndarray, 1d
The domain of the data points.
y: numpy.ndarray, 1d
The range of the data pints.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is required
for that mark, axes_options['x'] contains optional keyword arguments
for the constructor of the corresponding axis type.
"""
kwargs['orientation'] = "horizontal"
return bar(*args, **kwargs)
@_process_data('color')
def pie(sizes, **kwargs):
"""Draws a Pie in the current context figure.
Parameters
----------
sizes: numpy.ndarray, 1d
The proportions to be represented by the Pie.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is required
for that mark, axes_options['x'] contains optional keyword arguments
for the constructor of the corresponding axis type.
"""
kwargs['sizes'] = sizes
return _draw_mark(Pie, **kwargs)
def label(text, **kwargs):
"""Draws a Label in the current context figure.
Parameters
----------
text: string
The label to be displayed.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is required
for that mark, axes_options['x'] contains optional keyword arguments
for the constructor of the corresponding axis type.
"""
kwargs['text'] = text
return _draw_mark(Label, **kwargs)
def geo(map_data, **kwargs):
"""Draw a map in the current context figure.
Parameters
----------
map_data: string or bqplot.map (default: WorldMap)
Name of the map or json file required for the map data.
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required for that mark, options['x'] contains optional keyword
arguments for the constructor of the corresponding scale type.
axes_options: dict (default: {})
Options for the axes to be created. If an axis labeled 'x' is required
for that mark, axes_options['x'] contains optional keyword arguments
for the constructor of the corresponding axis type.
"""
scales = kwargs.pop('scales', _context['scales'])
options = kwargs.get('options', {})
if 'projection' not in scales:
scales['projection'] = Mercator(**options.get('projection', {}))
kwargs['scales'] = scales
if isinstance(map_data, string_types):
kwargs['map_data'] = topo_load('map_data/' + map_data + '.json')
else: