Skip to content

Commit 7206d0c

Browse files
committed
DOC: explain too many ticks
1 parent 0fc7c4b commit 7206d0c

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

doc/users/faq/howto_faq.rst

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,65 @@ How-to
99
.. contents::
1010
:backlinks: none
1111

12+
13+
_how-to-too-many-ticks
14+
15+
Why do I have so many ticks, and/or why are they out of order?
16+
--------------------------------------------------------------
17+
18+
Sometimes Matplotlib will unexpectedly plot with a tick for each data point,
19+
and/or the ticks will be out of numerical order. This is usually a sign that you
20+
have passed in a list of strings rather than a list or array of floats or
21+
datetime objects. This will often happen when reading in a comma-delimited text
22+
file. Matplotlib treats lists of strings as "categorical" variables
23+
(:doc:`/examples/lines_bars_and_markers/categorical_variables`), and by default
24+
puts one tick per "category", and plots them in the order in which they are
25+
supplied.
26+
27+
In the example below, the upper row plots are plotted using strings for *x*;
28+
note that each string gets a tick, and they are in the order of the list passed
29+
to Matplotlib. In the lower row the data is converted to either floats or
30+
datetime64; note that the ticks are now ordered and spaced numerically.
31+
32+
.. plot::
33+
:include-source:
34+
:align: center
35+
36+
import matplotlib.pyplot as plt
37+
import numpy as np
38+
39+
fig, ax = plt.subplots(2, 2, constrained_layout=True, figsize=(6, 6))
40+
x = ['1', '5', '2', '3']
41+
y = [1, 4, 2, 3]
42+
ax[0, 0].plot(x, y, 'd')
43+
ax[0, 0].set_xlabel('Categories')
44+
# convert to numbers:
45+
x = np.asarray(x, dtype='float')
46+
ax[1, 0].plot(x, y, 'd')
47+
ax[1, 0].set_xlabel('Floats')
48+
49+
x = ['2021-10-01', '2021-11-02', '2021-12-03', '2021-10-04']
50+
y = [0, 2, 3, 1]
51+
ax[0, 1].plot(x, y, 'd')
52+
ax[0, 1].tick_params(axis='x', labelrotation=45)
53+
# convert to datetime64
54+
x = np.asarray(x, dtype='datetime64[s]')
55+
ax[1, 1].plot(x, y, 'd')
56+
ax[1, 1].tick_params(axis='x', labelrotation=45)
57+
58+
If *x* has 100 elements, all strings, then we would have 100 (unreadable)
59+
ticks:
60+
61+
.. plot::
62+
import matplotlib.pyplot as plt
63+
import numpy as np
64+
65+
fig, ax = plt.subplots(figsize=(6, 2.5))
66+
x = [f'{xx}' for xx in np.arange(100)]
67+
y = np.arange(100)
68+
ax.plot(x, y)
69+
70+
1271
.. _howto-figure-empty:
1372

1473
Check whether a figure is empty

0 commit comments

Comments
 (0)