File tree Expand file tree Collapse file tree
examples/ticks_and_spines Expand file tree Collapse file tree Original file line number Diff line number Diff line change 99In this case may be better to determine the tick label from the value
1010at 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
2121import matplotlib .pyplot as plt
22- from matplotlib .ticker import FuncFormatter
22+ from matplotlib .ticker import FuncFormatter , MaxNLocator
23+
2324
2425fig = plt .figure ()
2526ax = fig .add_subplot (111 )
2627xs = range (26 )
2728ys = range (26 )
2829labels = 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
3338ax .xaxis .set_major_formatter (FuncFormatter (format_fn ))
39+ ax .xaxis .set_major_locator (MaxNLocator (integer = True ))
3440
3541ax .plot (xs , ys )
3642plt .show ()
You can’t perform that action at this time.
0 commit comments