Skip to content

Commit 6c83304

Browse files
committed
Merge pull request matplotlib#5063 from cammil/master
DOC: added tick labels from values demo
2 parents b900c8a + 51ec46c commit 6c83304

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
3+
Basic demo showing how to set tick labels to values of a series.
4+
5+
Using ax.set_xticks causes the tick labels to be set on the currently
6+
chosen ticks. However, you may want to allow matplotlib to dynamically
7+
choose the number of ticks and their spacing.
8+
9+
In this case may be better to determine the tick label from the value
10+
at the tick. The following example shows how to do this.
11+
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
16+
17+
"""
18+
19+
import matplotlib.pyplot as plt
20+
from matplotlib.ticker import FuncFormatter, MaxNLocator
21+
fig = plt.figure()
22+
ax = fig.add_subplot(111)
23+
xs = range(26)
24+
ys = range(26)
25+
labels = list('abcdefghijklmnopqrstuvwxyz')
26+
27+
28+
def format_fn(tick_val, tick_pos):
29+
if int(tick_val) in xs:
30+
return labels[int(tick_val)]
31+
else:
32+
return ''
33+
ax.xaxis.set_major_formatter(FuncFormatter(format_fn))
34+
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
35+
ax.plot(xs, ys)
36+
plt.show()

0 commit comments

Comments
 (0)