|
| 1 | +Support callable for formatting of Sankey labels |
| 2 | +------------------------------------------------ |
| 3 | + |
| 4 | +The `format` parameter of `matplotlib.sankey.Sankey` can now accept callables. |
| 5 | + |
| 6 | +This allows the use of an arbitrary function to label flows, for example allowing |
| 7 | +the mapping of numbers to emoji. |
| 8 | + |
| 9 | +.. plot:: |
| 10 | + |
| 11 | + import matplotlib.pyplot as plt |
| 12 | + from matplotlib.sankey import Sankey |
| 13 | + import math |
| 14 | + |
| 15 | + # on Windows, this font may be necessary to display emojis |
| 16 | + plt.rcParams['font.family'] = "Segoe UI Emoji" |
| 17 | + |
| 18 | + def display_in_cats(values, min_cats, max_cats): |
| 19 | + |
| 20 | + def display_in_cat_scale(value): |
| 21 | + max_value = max(values, key=abs) |
| 22 | + number_cats_to_show = max(min_cats, math.floor(abs(value) / max_value * max_cats)) |
| 23 | + return str(number_cats_to_show * '🐈') |
| 24 | + |
| 25 | + return display_in_cat_scale |
| 26 | + |
| 27 | + flows = [35, 15, 40, -20, -15, -5, -40, -10] |
| 28 | + orientations = [-1, 1, 0, 1, 1, 1, -1, -1] |
| 29 | + |
| 30 | + # Cats are good, we want a strictly positive number of them |
| 31 | + min_cats = 1 |
| 32 | + # More than four cats might be too much for some people |
| 33 | + max_cats = 4 |
| 34 | + |
| 35 | + cats_format = display_in_cats(flows, min_cats, max_cats) |
| 36 | + |
| 37 | + sankey = Sankey(flows=flows, orientations=orientations, format=cats_format, |
| 38 | + offset=.1, head_angle=180, shoulder=0, scale=.010) |
| 39 | + |
| 40 | + diagrams = sankey.finish() |
| 41 | + |
| 42 | + diagrams[0].texts[2].set_text('') |
| 43 | + |
| 44 | + plt.title(f'Sankey flows measured in cats \n🐈 = {max(flows, key=abs) / max_cats}') |
| 45 | + |
| 46 | + plt.show() |
0 commit comments