Skip to content

Use Axes.tick_params/Axis.set_tick_params more #8678

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 13, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 22 additions & 9 deletions doc/faq/howto_faq.rst
Original file line number Diff line number Diff line change
Expand Up @@ -241,21 +241,34 @@ over so that the tick labels fit in the figure:

.. _howto-ticks:

Configure the tick linewidths
-----------------------------
Configure the tick widths
-------------------------

In Matplotlib, the ticks are *markers*. All
:class:`~matplotlib.lines.Line2D` objects support a line (solid,
dashed, etc) and a marker (circle, square, tick). The tick linewidth
is controlled by the "markeredgewidth" property::
Wherever possible, it is recommended to use the :meth:`~Axes.tick_params` or
:meth:`~Axis.set_tick_params` methods to modify tick properties::

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

fig, ax = plt.subplots()
ax.plot(range(10))

ax.tick_params(width=10)

plt.show()

For more control of tick properties that are not provided by the above methods,
it is important to know that in Matplotlib, the ticks are *markers*. All
:class:`~matplotlib.lines.Line2D` objects support a line (solid, dashed, etc)
and a marker (circle, square, tick). The tick width is controlled by the
``"markeredgewidth"`` property, so the above effect can also be achieved by::

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

for line in ax.get_xticklines() + ax.get_yticklines():
line.set_markersize(10)
line.set_markeredgewidth(10)

plt.show()

Expand Down
12 changes: 4 additions & 8 deletions examples/api/logos2.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,10 @@ def add_polar_bar():
bar.set_facecolor(cm.jet(r/10.))
bar.set_alpha(0.6)

for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_visible(False)

for line in ax.get_ygridlines() + ax.get_xgridlines():
line.set_lw(0.8)
line.set_alpha(0.9)
line.set_ls('-')
line.set_color('0.5')
ax.tick_params(labelbottom=False, labeltop=False,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had no idea this was possible...cool!

labelleft=False, labelright=False)

ax.grid(lw=0.8, alpha=0.9, ls='-', color='0.5')

ax.set_yticks(np.arange(1, 9, 2))
ax.set_rmax(9)
Expand Down
7 changes: 2 additions & 5 deletions examples/axes_grid1/demo_axes_divider.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,7 @@ def demo_locatable_axes_easy(ax):

plt.colorbar(im, cax=ax_cb)
ax_cb.yaxis.tick_right()
for tl in ax_cb.get_yticklabels():
tl.set_visible(False)
ax_cb.yaxis.tick_right()
ax_cb.yaxis.set_tick_params(labelright=False)


def demo_images_side_by_side(ax):
Expand All @@ -94,8 +92,7 @@ def demo_images_side_by_side(ax):

ax.imshow(Z, extent=extent, interpolation="nearest")
ax2.imshow(Z, extent=extent, interpolation="nearest")
for tl in ax2.get_yticklabels():
tl.set_visible(False)
ax2.yaxis.set_tick_params(labelleft=False)


def demo():
Expand Down
10 changes: 2 additions & 8 deletions examples/axes_grid1/scatter_hist.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@
axHisty = divider.append_axes("right", 1.2, pad=0.1, sharey=axScatter)

# make some labels invisible
plt.setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(),
visible=False)
axHistx.xaxis.set_tick_params(labelbottom=False)
axHisty.yaxis.set_tick_params(labelleft=False)

# now determine nice limits by hand:
binwidth = 0.25
Expand All @@ -47,14 +47,8 @@
# thus there is no need to manually adjust the xlim and ylim of these
# axis.

#axHistx.axis["bottom"].major_ticklabels.set_visible(False)
for tl in axHistx.get_xticklabels():
tl.set_visible(False)
axHistx.set_yticks([0, 50, 100])

#axHisty.axis["left"].major_ticklabels.set_visible(False)
for tl in axHisty.get_yticklabels():
tl.set_visible(False)
axHisty.set_xticks([0, 50, 100])

plt.draw()
Expand Down
3 changes: 1 addition & 2 deletions examples/axes_grid1/simple_axes_divider2.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
ax[3].set_axes_locator(divider.new_locator(nx=2, nx1=4, ny=0))

for ax1 in ax:
plt.setp(ax1.get_xticklabels()+ax1.get_yticklabels(),
visible=False)
ax1.tick_params(labelbottom=False, labelleft=False)

plt.show()
3 changes: 1 addition & 2 deletions examples/axes_grid1/simple_axes_divider3.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
divider.set_aspect(1.)

for ax1 in ax:
plt.setp(ax1.get_xticklabels()+ax1.get_yticklabels(),
visible=False)
ax1.tick_params(labelbottom=False, labelleft=False)

plt.show()
5 changes: 1 addition & 4 deletions examples/misc/patheffect_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,9 @@
PathEffects.Stroke(linewidth=5, foreground="w"),
PathEffects.Normal()])

ax1.grid(True, linestyle="-")

pe = [PathEffects.withStroke(linewidth=3,
foreground="w")]
for l in ax1.get_xgridlines() + ax1.get_ygridlines():
l.set_path_effects(pe)
ax1.grid(True, linestyle="-", path_effects=pe)

ax2 = plt.subplot(132)
arr = np.arange(25).reshape((5, 5))
Expand Down
3 changes: 1 addition & 2 deletions examples/misc/pythonic_matplotlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@
ax1.set_ylabel('1 Hz')
ax1.set_title('A sine wave or two')

for label in ax1.get_xticklabels():
label.set_color('r')
ax1.xaxis.set_tick_params(labelcolor='r')


ax2 = fig.add_subplot(212)
Expand Down
17 changes: 3 additions & 14 deletions examples/subplots_axes_and_figures/axes_props.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,11 @@

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)
ax.grid(True)

ticklines = ax.get_xticklines() + ax.get_yticklines()
gridlines = ax.get_xgridlines() + ax.get_ygridlines()
ticklabels = ax.get_xticklabels() + ax.get_yticklabels()

for line in ticklines:
line.set_linewidth(3)

for line in gridlines:
line.set_linestyle('-.')

for label in ticklabels:
label.set_color('r')
label.set_fontsize('medium')
ax.grid(True, linestyle='-.')
ax.tick_params(labelcolor='r', labelsize='medium', width=3)

plt.show()
4 changes: 1 addition & 3 deletions examples/ticks_and_spines/centered_ticklabels.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
associates a label with a tick, and the label can be aligned
'center', 'left', or 'right' using the horizontal alignment property::


for label in ax.xaxis.get_xticklabels():
label.set_horizontalalignment('right')
ax.xaxis.set_tick_params(horizontalalignment='right')

but this doesn't help center the label between ticks. One solution
is to "fake it". Use the minor ticks to place a tick centered
Expand Down
3 changes: 1 addition & 2 deletions examples/ticks_and_spines/date_demo_rrule.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
plt.plot_date(dates, s)
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(formatter)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=30, fontsize=10)
ax.xaxis.set_tick_params(rotation=30, labelsize=10)

plt.show()
3 changes: 1 addition & 2 deletions examples/userdemo/demo_gridspec01.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
def make_ticklabels_invisible(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
for tl in ax.get_xticklabels() + ax.get_yticklabels():
tl.set_visible(False)
ax.tick_params(labelbottom=False, labelleft=False)


fig = plt.figure(0)
Expand Down
3 changes: 1 addition & 2 deletions examples/userdemo/demo_gridspec02.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
def make_ticklabels_invisible(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
for tl in ax.get_xticklabels() + ax.get_yticklabels():
tl.set_visible(False)
ax.tick_params(labelbottom=False, labelleft=False)


fig = plt.figure()
Expand Down
3 changes: 1 addition & 2 deletions examples/userdemo/demo_gridspec03.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
def make_ticklabels_invisible(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
for tl in ax.get_xticklabels() + ax.get_yticklabels():
tl.set_visible(False)
ax.tick_params(labelbottom=False, labelleft=False)


# demo 3 : gridspec with subplotpars set.
Expand Down
3 changes: 1 addition & 2 deletions examples/userdemo/demo_gridspec04.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
def make_ticklabels_invisible(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
for tl in ax.get_xticklabels() + ax.get_yticklabels():
tl.set_visible(False)
ax.tick_params(labelbottom=False, labelleft=False)


# gridspec inside gridspec
Expand Down
3 changes: 1 addition & 2 deletions examples/userdemo/demo_gridspec05.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
def make_ticklabels_invisible(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
for tl in ax.get_xticklabels() + ax.get_yticklabels():
tl.set_visible(False)
ax.tick_params(labelbottom=False, labelleft=False)


f = plt.figure()
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1173,14 +1173,14 @@ def subplots(self, nrows=1, ncols=1, sharex=False, sharey=False,
if sharex in ["col", "all"]:
# turn off all but the bottom row
for ax in axarr[:-1, :].flat:
for label in ax.get_xticklabels():
label.set_visible(False)
ax.xaxis.set_tick_params(which='both',
labelbottom=False, labeltop=False)
ax.xaxis.offsetText.set_visible(False)
if sharey in ["row", "all"]:
# turn off all but the first column
for ax in axarr[:, 1:].flat:
for label in ax.get_yticklabels():
label.set_visible(False)
ax.yaxis.set_tick_params(which='both',
labelleft=False, labelright=False)
ax.yaxis.offsetText.set_visible(False)

if squeeze:
Expand Down
14 changes: 6 additions & 8 deletions lib/matplotlib/tests/test_colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,14 @@ def _colorbar_extension_shape(spacing):
boundaries = values = norm.boundaries
# Create a subplot.
cax = fig.add_subplot(4, 1, i + 1)
# Turn off text and ticks.
for item in cax.get_xticklabels() + cax.get_yticklabels() +\
cax.get_xticklines() + cax.get_yticklines():
item.set_visible(False)
# Generate the colorbar.
cb = ColorbarBase(cax, cmap=cmap, norm=norm,
boundaries=boundaries, values=values,
extend=extension_type, extendrect=True,
orientation='horizontal', spacing=spacing)
# Turn off text and ticks.
cax.tick_params(left=False, labelleft=False,
bottom=False, labelbottom=False)
# Return the figure to the caller.
return fig

Expand All @@ -82,15 +81,14 @@ def _colorbar_extension_length(spacing):
for j, extendfrac in enumerate((None, 'auto', 0.1)):
# Create a subplot.
cax = fig.add_subplot(12, 1, i*3 + j + 1)
# Turn off text and ticks.
for item in cax.get_xticklabels() + cax.get_yticklabels() +\
cax.get_xticklines() + cax.get_yticklines():
item.set_visible(False)
# Generate the colorbar.
ColorbarBase(cax, cmap=cmap, norm=norm,
boundaries=boundaries, values=values,
extend=extension_type, extendfrac=extendfrac,
orientation='horizontal', spacing=spacing)
# Turn off text and ticks.
cax.tick_params(left=False, labelleft=False,
bottom=False, labelbottom=False)
# Return the figure to the caller.
return fig

Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,7 @@ def test_cmap_and_norm_from_levels_and_colors():
plt.colorbar(m)

# Hide the axes labels (but not the colorbar ones, as they are useful)
for lab in ax.get_xticklabels() + ax.get_yticklabels():
lab.set_visible(False)
ax.tick_params(labelleft=False, labelbottom=False)


def test_cmap_and_norm_from_levels_and_colors2():
Expand Down
21 changes: 21 additions & 0 deletions lib/matplotlib/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,3 +298,24 @@ def test_invalid_figure_size():

with pytest.raises(ValueError):
fig.add_axes((.1, .1, .5, np.nan))


def test_subplots_shareax_loglabels():
fig, ax_arr = plt.subplots(2, 2, sharex=True, sharey=True, squeeze=False)
for ax in ax_arr.flatten():
ax.plot([10, 20, 30], [10, 20, 30])

ax.set_yscale("log")
ax.set_xscale("log")

for ax in ax_arr[0, :]:
assert 0 == len(ax.xaxis.get_ticklabels(which='both'))

for ax in ax_arr[1, :]:
assert 0 < len(ax.xaxis.get_ticklabels(which='both'))

for ax in ax_arr[:, 1]:
assert 0 == len(ax.yaxis.get_ticklabels(which='both'))

for ax in ax_arr[:, 0]:
assert 0 < len(ax.yaxis.get_ticklabels(which='both'))
5 changes: 1 addition & 4 deletions lib/matplotlib/tests/test_patheffects.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,8 @@ def test_patheffect1():
foreground="w"),
path_effects.Normal()])

ax1.grid(True, linestyle="-")

pe = [path_effects.withStroke(linewidth=3, foreground="w")]
for l in ax1.get_xgridlines() + ax1.get_ygridlines():
l.set_path_effects(pe)
ax1.grid(True, linestyle="-", path_effects=pe)


@image_comparison(baseline_images=['patheffect2'], remove_text=True)
Expand Down
8 changes: 3 additions & 5 deletions tools/make_icons.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,9 @@ def make_matplotlib_icon():
for r, bar in zip(radii, bars):
bar.set_facecolor(cm.jet(r/10.))

for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_visible(False)

for line in ax.get_ygridlines() + ax.get_xgridlines():
line.set_lw(0.0)
ax.tick_params(labelleft=False, labelright=False,
labelbottom=False, labeltop=False)
ax.grid(lw=0.0)

ax.set_yticks(np.arange(1, 9, 2))
ax.set_rmax(9)
Expand Down