Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 59c53c2

Browse files
committed
Faster categorical tick formatter.
Having thousands of categories is most likely a sign that the user forgot to convert strings to floats or dates, but we may as well not take forever to generate the incorrect plot so that they can observe the failure faster. Right now StrCategoryFormatter constructs the value-to-label dict at every call to `__call__` which leads to quadratic complexity when iterating over the ticks. Instead, just do this once in `format_ticks` (and let `__call__` use that implementation too), for linear complexity. This speeds up from pylab import * cats = [str(x) for x in np.random.rand(4000)] # Bunch of labels. plt.plot(cats) plt.gcf().canvas.draw() from ~25s to ~11s (and the difference gets bigger for more ticks as we're comparing O(n^2) to O(n) (modulo dict lookup terms in log(n), probably)). The other option was to make UnitData maintain both a forward and a backward mapping in sync but this would require passing the UnitData instance rather than the mapping to the StrCategoryFormatter constructor and the API break is just not worth it.
1 parent bc4c4cc commit 59c53c2

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

lib/matplotlib/category.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -148,11 +148,11 @@ def __init__(self, units_mapping):
148148
self._units = units_mapping
149149

150150
def __call__(self, x, pos=None):
151-
if pos is None:
152-
return ""
153-
r_mapping = {v: StrCategoryFormatter._text(k)
154-
for k, v in self._units.items()}
155-
return r_mapping.get(int(np.round(x)), '')
151+
return '' if pos is None else self.format_ticks([x])[0]
152+
153+
def format_ticks(self, values):
154+
r_mapping = {v: self._text(k) for k, v in self._units.items()}
155+
return [r_mapping.get(round(val), '') for val in values]
156156

157157
@staticmethod
158158
def _text(value):

0 commit comments

Comments
 (0)