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

Skip to content

Commit 7e44f35

Browse files
committed
ensure integer value ticks
1 parent 9cba700 commit 7e44f35

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

examples/ticks_and_spines/tick_labels_from_values.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,28 +9,34 @@
99
In this case may be better to determine the tick label from the value
1010
at the tick. The following example shows how to do this.
1111
12-
NB: You may want to combine the solution below with
13-
`xaxis.set_major_locator(MaxNLocator(integer=True))` to ensure
14-
that tick values are always at integer values, and therefore always use
15-
the appropriate label.
12+
NB: The MaxNLocator is used here to ensure that the tick
13+
values take integer values. As such, we need to catch
14+
any IndexErrors in the format function where we have not
15+
defined a label for that particular tick
1616
1717
"""
1818

1919

2020

2121
import matplotlib.pyplot as plt
22-
from matplotlib.ticker import FuncFormatter
22+
from matplotlib.ticker import FuncFormatter, MaxNLocator
23+
2324

2425
fig = plt.figure()
2526
ax = fig.add_subplot(111)
2627
xs = range(26)
2728
ys = range(26)
2829
labels = list('abcdefghijklmnopqrstuvwxyz')
2930

30-
def format_fn(tick_val, tick_pos):
31-
return labels[int(tick_val)]
31+
def format_fn(tick_val, tick_pos):
32+
try:
33+
return labels[int(tick_val)]
34+
except IndexError:
35+
# no label for this tick
36+
return ''
3237

3338
ax.xaxis.set_major_formatter(FuncFormatter(format_fn))
39+
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
3440

3541
ax.plot(xs, ys)
3642
plt.show()

0 commit comments

Comments
 (0)