|
9 | 9 | .. contents::
|
10 | 10 | :backlinks: none
|
11 | 11 |
|
| 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 | + |
12 | 71 | .. _howto-figure-empty:
|
13 | 72 |
|
14 | 73 | Check whether a figure is empty
|
|
0 commit comments