forked from plotly/plotly.py
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmpltools.py
610 lines (499 loc) · 20.2 KB
/
mpltools.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
"""
Tools
A module for converting from mpl language to plotly language.
"""
importmath
importwarnings
importmatplotlib.dates
defcheck_bar_match(old_bar, new_bar):
"""Check if two bars belong in the same collection (bar chart).
Positional arguments:
old_bar -- a previously sorted bar dictionary.
new_bar -- a new bar dictionary that needs to be sorted.
"""
tests= []
tests+= (new_bar["orientation"] ==old_bar["orientation"],)
tests+= (new_bar["facecolor"] ==old_bar["facecolor"],)
ifnew_bar["orientation"] =="v":
new_width=new_bar["x1"] -new_bar["x0"]
old_width=old_bar["x1"] -old_bar["x0"]
tests+= (new_width-old_width<0.000001,)
tests+= (new_bar["y0"] ==old_bar["y0"],)
elifnew_bar["orientation"] =="h":
new_height=new_bar["y1"] -new_bar["y0"]
old_height=old_bar["y1"] -old_bar["y0"]
tests+= (new_height-old_height<0.000001,)
tests+= (new_bar["x0"] ==old_bar["x0"],)
ifall(tests):
returnTrue
else:
returnFalse
defcheck_corners(inner_obj, outer_obj):
inner_corners=inner_obj.get_window_extent().corners()
outer_corners=outer_obj.get_window_extent().corners()
ifinner_corners[0][0] <outer_corners[0][0]:
returnFalse
elifinner_corners[0][1] <outer_corners[0][1]:
returnFalse
elifinner_corners[3][0] >outer_corners[3][0]:
returnFalse
elifinner_corners[3][1] >outer_corners[3][1]:
returnFalse
else:
returnTrue
defconvert_dash(mpl_dash):
"""Convert mpl line symbol to plotly line symbol and return symbol."""
ifmpl_dashinDASH_MAP:
returnDASH_MAP[mpl_dash]
else:
dash_array=mpl_dash.split(",")
iflen(dash_array) <2:
return"solid"
# Catch the exception where the off length is zero, in case
# matplotlib 'solid' changes from '10,0' to 'N,0'
ifmath.isclose(float(dash_array[1]), 0.0):
return"solid"
# If we can't find the dash pattern in the map, convert it
# into custom values in px, e.g. '7,5' -> '7px,5px'
dashpx=",".join([x+"px"forxindash_array])
# TODO: rewrite the convert_dash code
# only strings 'solid', 'dashed', etc allowed
ifdashpx=="7.4px,3.2px":
dashpx="dashed"
elifdashpx=="12.8px,3.2px,2.0px,3.2px":
dashpx="dashdot"
elifdashpx=="2.0px,3.3px":
dashpx="dotted"
returndashpx
defconvert_path(path):
verts=path[0] # may use this later
code=tuple(path[1])
ifcodeinPATH_MAP:
returnPATH_MAP[code]
else:
returnNone
defconvert_symbol(mpl_symbol):
"""Convert mpl marker symbol to plotly symbol and return symbol."""
ifisinstance(mpl_symbol, list):
symbol=list()
forsinmpl_symbol:
symbol+= [convert_symbol(s)]
returnsymbol
elifmpl_symbolinSYMBOL_MAP:
returnSYMBOL_MAP[mpl_symbol]
else:
return"circle"# default
defhex_to_rgb(value):
"""
Change a hex color to an rgb tuple
:param (str|unicode) value: The hex string we want to convert.
:return: (int, int, int) The red, green, blue int-tuple.
Example:
'#FFFFFF' --> (255, 255, 255)
"""
value=value.lstrip("#")
lv=len(value)
returntuple(int(value[i : i+lv//3], 16) foriinrange(0, lv, lv//3))
defmerge_color_and_opacity(color, opacity):
"""
Merge hex color with an alpha (opacity) to get an rgba tuple.
:param (str|unicode) color: A hex color string.
:param (float|int) opacity: A value [0, 1] for the 'a' in 'rgba'.
:return: (int, int, int, float) The rgba color and alpha tuple.
"""
ifcolorisNone: # None can be used as a placeholder, just bail.
returnNone
rgb_tup=hex_to_rgb(color)
ifopacityisNone:
return"rgb {}".format(rgb_tup)
rgba_tup=rgb_tup+ (opacity,)
return"rgba {}".format(rgba_tup)
defconvert_va(mpl_va):
"""Convert mpl vertical alignment word to equivalent HTML word.
Text alignment specifiers from mpl differ very slightly from those used
in HTML. See the VA_MAP for more details.
Positional arguments:
mpl_va -- vertical mpl text alignment spec.
"""
ifmpl_vainVA_MAP:
returnVA_MAP[mpl_va]
else:
returnNone# let plotly figure it out!
defconvert_x_domain(mpl_plot_bounds, mpl_max_x_bounds):
"""Map x dimension of current plot to plotly's domain space.
The bbox used to locate an axes object in mpl differs from the
method used to locate axes in plotly. The mpl version locates each
axes in the figure so that axes in a single-plot figure might have
the bounds, [0.125, 0.125, 0.775, 0.775] (x0, y0, width, height),
in mpl's figure coordinates. However, the axes all share one space in
plotly such that the domain will always be [0, 0, 1, 1]
(x0, y0, x1, y1). To convert between the two, the mpl figure bounds
need to be mapped to a [0, 1] domain for x and y. The margins set
upon opening a new figure will appropriately match the mpl margins.
Optionally, setting margins=0 and simply copying the domains from
mpl to plotly would place axes appropriately. However,
this would throw off axis and title labeling.
Positional arguments:
mpl_plot_bounds -- the (x0, y0, width, height) params for current ax **
mpl_max_x_bounds -- overall (x0, x1) bounds for all axes **
** these are all specified in mpl figure coordinates
"""
mpl_x_dom= [mpl_plot_bounds[0], mpl_plot_bounds[0] +mpl_plot_bounds[2]]
plotting_width=mpl_max_x_bounds[1] -mpl_max_x_bounds[0]
x0= (mpl_x_dom[0] -mpl_max_x_bounds[0]) /plotting_width
x1= (mpl_x_dom[1] -mpl_max_x_bounds[0]) /plotting_width
return [x0, x1]
defconvert_y_domain(mpl_plot_bounds, mpl_max_y_bounds):
"""Map y dimension of current plot to plotly's domain space.
The bbox used to locate an axes object in mpl differs from the
method used to locate axes in plotly. The mpl version locates each
axes in the figure so that axes in a single-plot figure might have
the bounds, [0.125, 0.125, 0.775, 0.775] (x0, y0, width, height),
in mpl's figure coordinates. However, the axes all share one space in
plotly such that the domain will always be [0, 0, 1, 1]
(x0, y0, x1, y1). To convert between the two, the mpl figure bounds
need to be mapped to a [0, 1] domain for x and y. The margins set
upon opening a new figure will appropriately match the mpl margins.
Optionally, setting margins=0 and simply copying the domains from
mpl to plotly would place axes appropriately. However,
this would throw off axis and title labeling.
Positional arguments:
mpl_plot_bounds -- the (x0, y0, width, height) params for current ax **
mpl_max_y_bounds -- overall (y0, y1) bounds for all axes **
** these are all specified in mpl figure coordinates
"""
mpl_y_dom= [mpl_plot_bounds[1], mpl_plot_bounds[1] +mpl_plot_bounds[3]]
plotting_height=mpl_max_y_bounds[1] -mpl_max_y_bounds[0]
y0= (mpl_y_dom[0] -mpl_max_y_bounds[0]) /plotting_height
y1= (mpl_y_dom[1] -mpl_max_y_bounds[0]) /plotting_height
return [y0, y1]
defdisplay_to_paper(x, y, layout):
"""Convert mpl display coordinates to plotly paper coordinates.
Plotly references object positions with an (x, y) coordinate pair in either
'data' or 'paper' coordinates which reference actual data in a plot or
the entire plotly axes space where the bottom-left of the bottom-left
plot has the location (x, y) = (0, 0) and the top-right of the top-right
plot has the location (x, y) = (1, 1). Display coordinates in mpl reference
objects with an (x, y) pair in pixel coordinates, where the bottom-left
corner is at the location (x, y) = (0, 0) and the top-right corner is at
the location (x, y) = (figwidth*dpi, figheight*dpi). Here, figwidth and
figheight are in inches and dpi are the dots per inch resolution.
"""
num_x=x-layout["margin"]["l"]
den_x=layout["width"] - (layout["margin"]["l"] +layout["margin"]["r"])
num_y=y-layout["margin"]["b"]
den_y=layout["height"] - (layout["margin"]["b"] +layout["margin"]["t"])
returnnum_x/den_x, num_y/den_y
defget_axes_bounds(fig):
"""Return the entire axes space for figure.
An axes object in mpl is specified by its relation to the figure where
(0,0) corresponds to the bottom-left part of the figure and (1,1)
corresponds to the top-right. Margins exist in matplotlib because axes
objects normally don't go to the edges of the figure.
In plotly, the axes area (where all subplots go) is always specified with
the domain [0,1] for both x and y. This function finds the smallest box,
specified by two points, that all of the mpl axes objects fit into. This
box is then used to map mpl axes domains to plotly axes domains.
"""
x_min, x_max, y_min, y_max= [], [], [], []
foraxes_objinfig.get_axes():
bounds=axes_obj.get_position().bounds
x_min.append(bounds[0])
x_max.append(bounds[0] +bounds[2])
y_min.append(bounds[1])
y_max.append(bounds[1] +bounds[3])
x_min, y_min, x_max, y_max=min(x_min), min(y_min), max(x_max), max(y_max)
return (x_min, x_max), (y_min, y_max)
defget_axis_mirror(main_spine, mirror_spine):
ifmain_spineandmirror_spine:
return"ticks"
elifmain_spineandnotmirror_spine:
returnFalse
elifnotmain_spineandmirror_spine:
returnFalse# can't handle this case yet!
else:
returnFalse# nuttin'!
defget_bar_gap(bar_starts, bar_ends, tol=1e-10):
iflen(bar_starts) ==len(bar_ends) andlen(bar_starts) >1:
sides1=bar_starts[1:]
sides2=bar_ends[:-1]
gaps= [s2-s1fors2, s1inzip(sides1, sides2)]
gap0=gaps[0]
uniform=all([abs(gap0-gap) <tolforgapingaps])
ifuniform:
returngap0
defconvert_rgba_array(color_list):
clean_color_list=list()
forcincolor_list:
clean_color_list+= [
(dict(r=int(c[0] *255), g=int(c[1] *255), b=int(c[2] *255), a=c[3]))
]
plotly_colors=list()
forrgbainclean_color_list:
plotly_colors+= ["rgba({r},{g},{b},{a})".format(**rgba)]
iflen(plotly_colors) ==1:
returnplotly_colors[0]
else:
returnplotly_colors
defconvert_path_array(path_array):
symbols=list()
forpathinpath_array:
symbols+= [convert_path(path)]
iflen(symbols) ==1:
returnsymbols[0]
else:
returnsymbols
defconvert_linewidth_array(width_array):
iflen(width_array) ==1:
returnwidth_array[0]
else:
returnwidth_array
defconvert_size_array(size_array):
size= [math.sqrt(s) forsinsize_array]
iflen(size) ==1:
returnsize[0]
else:
returnsize
defget_markerstyle_from_collection(props):
markerstyle=dict(
alpha=None,
facecolor=convert_rgba_array(props["styles"]["facecolor"]),
marker=convert_path_array(props["paths"]),
edgewidth=convert_linewidth_array(props["styles"]["linewidth"]),
# markersize=convert_size_array(props['styles']['size']), # TODO!
markersize=convert_size_array(props["mplobj"].get_sizes()),
edgecolor=convert_rgba_array(props["styles"]["edgecolor"]),
)
returnmarkerstyle
defget_rect_xmin(data):
"""Find minimum x value from four (x,y) vertices."""
returnmin(data[0][0], data[1][0], data[2][0], data[3][0])
defget_rect_xmax(data):
"""Find maximum x value from four (x,y) vertices."""
returnmax(data[0][0], data[1][0], data[2][0], data[3][0])
defget_rect_ymin(data):
"""Find minimum y value from four (x,y) vertices."""
returnmin(data[0][1], data[1][1], data[2][1], data[3][1])
defget_rect_ymax(data):
"""Find maximum y value from four (x,y) vertices."""
returnmax(data[0][1], data[1][1], data[2][1], data[3][1])
defget_spine_visible(ax, spine_key):
"""Return some spine parameters for the spine, `spine_key`."""
spine=ax.spines[spine_key]
ax_frame_on=ax.get_frame_on()
position=spine._positionor ("outward", 0.0)
ifisinstance(position, str):
ifposition=="center":
position= ("axes", 0.5)
elifposition=="zero":
position= ("data", 0)
position_type, amount=position
ifposition_type=="outward"andamount==0:
spine_frame_like=True
else:
spine_frame_like=False
ifnotspine.get_visible():
returnFalse
elifnotspine._edgecolor[-1]: # user's may have set edgecolor alpha==0
returnFalse
elifnotax_frame_onandspine_frame_like:
returnFalse
elifax_frame_onandspine_frame_like:
returnTrue
elifnotax_frame_onandnotspine_frame_like:
returnTrue# we've already checked for that it's visible.
else:
returnFalse# oh man, and i thought we exhausted the options...
defis_bar(bar_containers, **props):
"""A test to decide whether a path is a bar from a vertical bar chart."""
# is this patch in a bar container?
forcontainerinbar_containers:
ifprops["mplobj"] incontainer:
returnTrue
returnFalse
defmake_bar(**props):
"""Make an intermediate bar dictionary.
This creates a bar dictionary which aids in the comparison of new bars to
old bars from other bar chart (patch) collections. This is not the
dictionary that needs to get passed to plotly as a data dictionary. That
happens in PlotlyRenderer in that class's draw_bar method. In other
words, this dictionary describes a SINGLE bar, whereas, plotly will
require a set of bars to be passed in a data dictionary.
"""
return {
"bar": props["mplobj"],
"x0": get_rect_xmin(props["data"]),
"y0": get_rect_ymin(props["data"]),
"x1": get_rect_xmax(props["data"]),
"y1": get_rect_ymax(props["data"]),
"alpha": props["style"]["alpha"],
"edgecolor": props["style"]["edgecolor"],
"facecolor": props["style"]["facecolor"],
"edgewidth": props["style"]["edgewidth"],
"dasharray": props["style"]["dasharray"],
"zorder": props["style"]["zorder"],
}
defprep_ticks(ax, index, ax_type, props):
"""Prepare axis obj belonging to axes obj.
positional arguments:
ax - the mpl axes instance
index - the index of the axis in `props`
ax_type - 'x' or 'y' (for now)
props - an mplexporter poperties dictionary
"""
axis_dict=dict()
ifax_type=="x":
axis=ax.get_xaxis()
elifax_type=="y":
axis=ax.get_yaxis()
else:
returndict() # whoops!
scale=props["axes"][index]["scale"]
ifscale=="linear":
# get tick location information
try:
tickvalues=props["axes"][index]["tickvalues"]
tick0=tickvalues[0]
dticks= [
round(tickvalues[i] -tickvalues[i-1], 12)
foriinrange(1, len(tickvalues) -1)
]
ifall([dticks[i] ==dticks[i-1] foriinrange(1, len(dticks) -1)]):
dtick=tickvalues[1] -tickvalues[0]
else:
warnings.warn(
"'linear' {0}-axis tick spacing not even, "
"ignoring mpl tick formatting.".format(ax_type)
)
raiseTypeError
except (IndexError, TypeError):
axis_dict["nticks"] =props["axes"][index]["nticks"]
else:
axis_dict["tick0"] =tick0
axis_dict["dtick"] =dtick
axis_dict["tickmode"] =None
elifscale=="log":
try:
axis_dict["tick0"] =props["axes"][index]["tickvalues"][0]
axis_dict["dtick"] = (
props["axes"][index]["tickvalues"][1]
-props["axes"][index]["tickvalues"][0]
)
axis_dict["tickmode"] =None
except (IndexError, TypeError):
axis_dict=dict(nticks=props["axes"][index]["nticks"])
base=axis.get_transform().base
ifbase==10:
ifax_type=="x":
axis_dict["range"] = [
math.log10(props["xlim"][0]),
math.log10(props["xlim"][1]),
]
elifax_type=="y":
axis_dict["range"] = [
math.log10(props["ylim"][0]),
math.log10(props["ylim"][1]),
]
else:
axis_dict=dict(range=None, type="linear")
warnings.warn(
"Converted non-base10 {0}-axis log scale to 'linear'""".format(ax_type)
)
else:
returndict()
# get tick label formatting information
formatter=axis.get_major_formatter().__class__.__name__
ifax_type=="x"and"DateFormatter"informatter:
axis_dict["type"] ="date"
try:
axis_dict["tick0"] =mpl_dates_to_datestrings(axis_dict["tick0"], formatter)
exceptKeyError:
pass
finally:
axis_dict.pop("dtick", None)
axis_dict.pop("tickmode", None)
axis_dict["range"] =mpl_dates_to_datestrings(props["xlim"], formatter)
ifformatter=="LogFormatterMathtext":
axis_dict["exponentformat"] ="e"
returnaxis_dict
defprep_xy_axis(ax, props, x_bounds, y_bounds):
xaxis=dict(
type=props["axes"][0]["scale"],
range=list(props["xlim"]),
showgrid=props["axes"][0]["grid"]["gridOn"],
domain=convert_x_domain(props["bounds"], x_bounds),
side=props["axes"][0]["position"],
tickfont=dict(size=props["axes"][0]["fontsize"]),
)
xaxis.update(prep_ticks(ax, 0, "x", props))
yaxis=dict(
type=props["axes"][1]["scale"],
range=list(props["ylim"]),
showgrid=props["axes"][1]["grid"]["gridOn"],
domain=convert_y_domain(props["bounds"], y_bounds),
side=props["axes"][1]["position"],
tickfont=dict(size=props["axes"][1]["fontsize"]),
)
yaxis.update(prep_ticks(ax, 1, "y", props))
returnxaxis, yaxis
defmpl_dates_to_datestrings(dates, mpl_formatter):
"""Convert matplotlib dates to iso-formatted-like time strings.
Plotly's accepted format: "YYYY-MM-DD HH:MM:SS" (e.g., 2001-01-01 00:00:00)
Info on mpl dates: http://matplotlib.org/api/dates_api.html
"""
_dates=dates
# this is a pandas datetime formatter, times show up in floating point days
# since the epoch (1970-01-01T00:00:00+00:00)
ifmpl_formatter=="TimeSeries_DateFormatter":
try:
dates=matplotlib.dates.epoch2num([date*24*60*60fordateindates])
dates=matplotlib.dates.num2date(dates)
except:
return_dates
# the rest of mpl dates are in floating point days since
# (0001-01-01T00:00:00+00:00) + 1. I.e., (0001-01-01T00:00:00+00:00) == 1.0
# according to mpl --> try num2date(1)
else:
try:
dates=matplotlib.dates.num2date(dates)
except:
return_dates
time_stings= [
" ".join(date.isoformat().split("+")[0].split("T")) fordateindates
]
returntime_stings
# dashed is dash in matplotlib
DASH_MAP= {
"10,0": "solid",
"6,6": "dash",
"2,2": "circle",
"4,4,2,4": "dashdot",
"none": "solid",
"7.4,3.2": "dash",
}
PATH_MAP= {
("M", "C", "C", "C", "C", "C", "C", "C", "C", "Z"): "o",
("M", "L", "L", "L", "L", "L", "L", "L", "L", "L", "Z"): "*",
("M", "L", "L", "L", "L", "L", "L", "L", "Z"): "8",
("M", "L", "L", "L", "L", "L", "Z"): "h",
("M", "L", "L", "L", "L", "Z"): "p",
("M", "L", "M", "L", "M", "L"): "1",
("M", "L", "L", "L", "Z"): "s",
("M", "L", "M", "L"): "+",
("M", "L", "L", "Z"): "^",
("M", "L"): "|",
}
SYMBOL_MAP= {
"o": "circle",
"v": "triangle-down",
"^": "triangle-up",
"<": "triangle-left",
">": "triangle-right",
"s": "square",
"+": "cross",
"x": "x",
"*": "star",
"D": "diamond",
"d": "diamond",
}
VA_MAP= {"center": "middle", "baseline": "bottom", "top": "top"}