|
| 1 | +import pytest |
| 2 | +import plotly.graph_objects as go |
| 3 | +from plotly.subplots import make_subplots |
| 4 | +from itertools import combinations, product |
| 5 | +from functools import reduce |
| 6 | + |
| 7 | + |
| 8 | +def all_combos(it): |
| 9 | + return list( |
| 10 | + reduce( |
| 11 | + lambda a, b: a + b, |
| 12 | + [list(combinations(it, r)) for r in range(1, len(it))], |
| 13 | + [], |
| 14 | + ) |
| 15 | + ) |
| 16 | + |
| 17 | + |
| 18 | +def translate_layout_keys(t): |
| 19 | + xr, yr = t |
| 20 | + xr = xr.replace("axis", "") |
| 21 | + yr = yr.replace("axis", "") |
| 22 | + return (xr, yr) |
| 23 | + |
| 24 | + |
| 25 | +def get_non_empty_subplots(fig, selector): |
| 26 | + gr = fig._validate_get_grid_ref() |
| 27 | + nrows = len(gr) |
| 28 | + ncols = len(gr[0]) |
| 29 | + sp_addresses = product(range(nrows), range(ncols)) |
| 30 | + # assign a number similar to plotly's xref/yref (e.g, xref=x2) to each |
| 31 | + # subplot address (xref=x -> 1, but xref=x3 -> 3) |
| 32 | + # sp_ax_numbers=range(1,len(sp_addresses)+1) |
| 33 | + # Get those subplot numbers which contain something |
| 34 | + ret = list( |
| 35 | + filter( |
| 36 | + lambda sp: fig._subplot_not_empty( |
| 37 | + *translate_layout_keys(sp.layout_keys), selector=selector |
| 38 | + ), |
| 39 | + [gr[r][c][0] for r, c in sp_addresses], |
| 40 | + ) |
| 41 | + ) |
| 42 | + return ret |
| 43 | + |
| 44 | + |
| 45 | +def test_choose_correct_non_empty_subplots(): |
| 46 | + # This checks to see that the correct subplots are selected for all |
| 47 | + # combinations of selectors |
| 48 | + fig = make_subplots(2, 2) |
| 49 | + fig.add_trace(go.Scatter(x=[1, 2], y=[3, 4]), row=1, col=1) |
| 50 | + fig.add_shape(dict(type="rect", x0=1, x1=2, y0=3, y1=4), row=1, col=2) |
| 51 | + fig.add_annotation(dict(text="A", x=1, y=2), row=2, col=1) |
| 52 | + fig.add_layout_image( |
| 53 | + dict(source="test", x=1, y=2, sizex=0.5, sizey=0.5), row=2, col=2 |
| 54 | + ) |
| 55 | + all_subplots = get_non_empty_subplots(fig, "all") |
| 56 | + selectors = all_combos(["traces", "shapes", "annotations", "images"]) |
| 57 | + subplot_combos = all_combos(all_subplots) |
| 58 | + for s, spc in zip(selectors, subplot_combos): |
| 59 | + sps = tuple(get_non_empty_subplots(fig, s)) |
| 60 | + assert sps == spc |
0 commit comments