38

Is there a way to increase the thickness and size of ticks in matplotlib without having to write a long piece of code like this:

for line in ax1.yaxis.get_ticklines():
    line.set_markersize(25)
    line.set_markeredgewidth(3)

The problem with this piece of code is that it uses a loop which costs usually a lot of CPU usage.

user1850133
  • 2,833
  • 9
  • 29
  • 39
  • very closely related to http://stackoverflow.com/questions/14711338/matplotlib-ticks-position-relative-to-axis – tacaswell Feb 05 '13 at 17:03

3 Answers3

57

A simpler way is to use the set_tick_params function of axis objects:

ax.xaxis.set_tick_params(width=5)
ax.yaxis.set_tick_params(width=5)

Doing it this way means you can change this on a per-axis basis with out worrying about global state and with out making any assumptions about the internal structure of mpl objects.

If you want to set this for all the ticks in your axes,

ax = plt.gca()
ax.tick_params(width=5,...)

Take a look at set_tick_params doc and tick_params valid keywords

tylerswright
  • 67
  • 2
  • 12
tacaswell
  • 84,579
  • 22
  • 210
  • 199
23

You can change all matplotlib defaults using rcParams like in

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

# set tick width
mpl.rcParams['xtick.major.size'] = 20
mpl.rcParams['xtick.major.width'] = 4
mpl.rcParams['xtick.minor.size'] = 10
mpl.rcParams['xtick.minor.width'] = 2

x = np.linspace(0., 10.)
plt.plot(x, np.sin(x))

plt.show()
Sheldore
  • 37,862
  • 7
  • 57
  • 71
David Zwicker
  • 23,581
  • 6
  • 62
  • 77
6

You can use matplotlib.pyplot.setp

plt.setp(ax.yaxis.get_ticklines(), 'markersize', 25)
plt.setp(ax.yaxis.get_ticklines(), 'markeredgewidth', 3)

You can also use list comprehension, although not having a return value probably does not make much sense, besides reducing the number of lines in the code see e.g. here

[line.set_markersize(25) for line in ax1.yaxis.get_ticklines()]
[line.set_markeredgewidth(3) for line in ax1.yaxis.get_ticklines()]
Francesco Montesano
  • 8,485
  • 2
  • 40
  • 64
  • why should a list comprehension be more efficient, if you never use the resulting list? – David Zwicker Feb 05 '13 at 15:59
  • 1
    You're right. If I've understood [this](http://blog.cdleary.com/2010/04/efficiency-of-list-comprehensions/) correctly, could be even worse (for efficiency and readability). I'll edit my answer. ps,OT: this is the demonstration that something like stackoverflow is a great tool as sometimes you learn more answering questions that asking them – Francesco Montesano Feb 05 '13 at 16:13