|
| 1 | +""" |
| 2 | +================================= |
| 3 | +Automatically setting tick labels |
| 4 | +================================= |
| 5 | +
|
| 6 | +Setting the behavior of tick auto-placement. |
| 7 | +
|
| 8 | +If you don't explicitly set tick positions / labels, Matplotlib will attempt |
| 9 | +to choose them both automatically based on the displayed data and its limits. |
| 10 | +
|
| 11 | +By default, this attempts to choose tick positions that are distributed |
| 12 | +along the axis: |
| 13 | +""" |
| 14 | +import matplotlib.pyplot as plt |
| 15 | +import numpy as np |
| 16 | +np.random.seed(19680801) |
| 17 | +rc = plt.rcParams |
| 18 | + |
| 19 | +fig, ax = plt.subplots() |
| 20 | +data = np.random.randn(2, 1000) |
| 21 | +ax.scatter(*data, c=data[1]) |
| 22 | + |
| 23 | +################################################################################ |
| 24 | +# if we change the X or Y limits, Matplotlib will automatically change the |
| 25 | +# ticks accordingly: |
| 26 | + |
| 27 | +fig, ax = plt.subplots() |
| 28 | +ax.scatter(*data, c=data[1]) |
| 29 | +xlim = [-.5, .5] |
| 30 | +ylim = [0, .3] |
| 31 | +ax.set(xlim=xlim, ylim=ylim) |
| 32 | + |
| 33 | +################################################################################ |
| 34 | +# Sometimes choosing evenly-distributed ticks results in strange tick positions. |
| 35 | +# If you'd like Matplotlib to keep ticks located at even numbers, you can |
| 36 | +# change this behavior with the following rcParams value: |
| 37 | + |
| 38 | +print(rc['axes.autolimit_mode']) |
| 39 | + |
| 40 | +# Now change this value and see the results |
| 41 | +rc['axes.autolimit_mode'] = 'round_numbers' |
| 42 | +with plt.rc_context(rc=rc): |
| 43 | + fig, ax = plt.subplots() |
| 44 | + ax.scatter(*data, c=data[1]) |
| 45 | + ax.set(xlim=xlim, ylim=ylim) |
| 46 | + |
| 47 | +################################################################################ |
| 48 | +# You can also alter the location of the ticks at the edge of each axis by |
| 49 | +# changing their margins: |
| 50 | + |
| 51 | +rc['axes.xmargin'] = 0 |
| 52 | +rc['axes.ymargin'] = 0 |
| 53 | + |
| 54 | +with plt.rc_context(rc=rc): |
| 55 | + fig, ax = plt.subplots() |
| 56 | + ax.scatter(*data, c=data[1]) |
| 57 | + ax.set(xlim=xlim, ylim=ylim) |
| 58 | + |
| 59 | +plt.show() |
0 commit comments