Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python matplotlib imshow() custom tickmarks

I'm trying to set custom tick marks on my imshow() output, but haven't found the right combination.

The script below summarizes my attempts. In this script, I'm trying to make the tickmarks at all even numbers on each axis instead of the default (-10,-5,0,5,10)

#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np

#Generate random histogram
N=25
middle=N/2
hist=np.random.random_sample((N,N))

#Ticks at even numbers, data centered at 0
ticks=np.arange(-middle,middle+2,2)

extent=(-middle,middle,-middle,middle)
plt.imshow(hist, interpolation='nearest', extent=extent, origin='lower')
plt.colorbar()

#
#These are my attempts to set the tick marks
#
#plt.gcf().gca().set_ticks(ticks)

#plt.gca().set_ticks(ticks)

#ax=plt.axes()
#ax.set_ticks(ticks)

plt.show()

I'm starting to get the feeling that set_ticks() might not be the way to do it, but I'm not sure what else to try.

Thanks!

like image 756
zje Avatar asked Feb 21 '12 18:02

zje


People also ask

How do I create a custom tick in MatPlotLib?

Set the figure size and adjust the padding between and around the subplots. Create lists for height, bars and y_pos data points. Make a bar plot using bar() method. To customize X-axis ticks, we can use tick_params() method, with color=red, direction=outward, length=7, and width=2.

How do I change the format of a tick in MatPlotLib?

Tick formatters can be set in one of two ways, either by passing a str or function to set_major_formatter or set_minor_formatter , or by creating an instance of one of the various Formatter classes and providing that to set_major_formatter or set_minor_formatter .

How do I create a minor tick in MatPlotLib?

Minor tick labels can be turned on by setting the minor formatter. MultipleLocator places ticks on multiples of some base. StrMethodFormatter uses a format string (e.g., '{x:d}' or '{x:1.2f}' or '{x:1.1f} cm' ) to format the tick labels (the variable in the format string must be 'x' ).


1 Answers

http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks

plt.xticks(ticks) # `ticks` is a list here!

Edit: as Yann mentions in a comment, you may also be interested in plt.yticks()

Result (using plt.xticks(ticks, fontsize=9)): enter image description here

like image 88
mechanical_meat Avatar answered Sep 17 '22 18:09

mechanical_meat