File: tick_labels_from_values.py

package info (click to toggle)
matplotlib 3.3.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 78,264 kB
  • sloc: python: 123,969; cpp: 57,655; ansic: 29,431; objc: 2,244; javascript: 757; makefile: 163; sh: 111
file content (57 lines) | stat: -rw-r--r-- 1,438 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
=========================================
Setting tick labels from a list of values
=========================================

Using `.Axes.set_xticks` causes the tick labels to be set on the currently
chosen ticks. However, you may want to allow matplotlib to dynamically
choose the number of ticks and their spacing.

In this case it may be better to determine the tick label from the
value at the tick. The following example shows how to do this.

NB: The `.ticker.MaxNLocator` is used here to ensure that the tick values
take integer values.

"""

import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator


fig, ax = plt.subplots()
xs = range(26)
ys = range(26)
labels = list('abcdefghijklmnopqrstuvwxyz')


def format_fn(tick_val, tick_pos):
    if int(tick_val) in xs:
        return labels[int(tick_val)]
    else:
        return ''


# A FuncFormatter is created automatically.
ax.xaxis.set_major_formatter(format_fn)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.plot(xs, ys)
plt.show()


#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:

import matplotlib
matplotlib.pyplot.subplots
matplotlib.axis.Axis.set_major_formatter
matplotlib.axis.Axis.set_major_locator
matplotlib.ticker.FuncFormatter
matplotlib.ticker.MaxNLocator