Custom ticks auto-scale when using imshow?

I am trying to change the imshow value on the chart along the x axis of imshow using the following code:

 import matplotlib.pyplot as plt import numpy as np def scale_xaxis(number): return(number+1001) data = np.array([range(10),range(10,20)]) fig = plt.figure(figsize=(3,5)) ax = fig.add_subplot(111) ax.imshow(data,aspect='auto') ax.autoscale(False) xticks = ax.get_xticks() ax.xaxis.set_ticklabels(scale_xaxis(xticks)) plt.savefig("test.png") 

Resulting Image http://ubuntuone.com/2Y5ujtlEkEnrlTcVUxvWLU

However, the x-ticks overlap and have a non-round value. Is there a way for matplotlib to automatically do this? Either using set_ticklabels , or in some other way?

+7
source share
2 answers

Also consider using extent (doc) so that matplotlib about how to place label tags and add an arbitrary shift:

 data = np.array([range(10),range(10,20)]) fig = plt.figure(figsize=(3,5)) ax = fig.add_subplot(111) ax.imshow(data,aspect='auto',extent=[10000,10010,0,1]) 

If you definitely want to do this on my part, you might be better off setting the formatter and locator axis to get what you want (doc) .

 import matplotlib.pyplot as plt import numpy as np def scale_xaxis(number): return(number+1001) def my_form(x,pos): return '%d'%scale_xaxis(x) data = np.array([range(10),range(10,20)]) fig = plt.figure(figsize=(3,5)) ax = fig.add_subplot(111) ax.imshow(data,aspect='auto') ax.autoscale(False) ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(int(2))) ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(my_form)) 

The locator must be configured to make sure that ticks do not fit into non-integer locations, which are then force converted to integers by formatting (which would leave them in the wrong place)

related issues:

matplotlib: format axis offset to integers or a specific number

remove lead 0 from matplotlib tag label format

+6
source

There are several ways to do this.

You can:

  • Pass an array from ints instead of a float array
  • Passing an array of formatted strings
  • Use custom ticket format

The last option is an excess for something so simple.

As an example of the first option, you modify your scale_xaxis function as follows:

 def scale_xaxis(numbers): return numbers.astype(int) + 1001 

Note that what you get from ax.get_xticks is a numpy array instead of a single value. So we need to do number.astype(int) instead of int(number) .

Alternatively, we can return a series of formatted strings. set_xticklabels actually expects a sequence of strings:

 def scale_xaxis(numbers): return ['{:0.0f}'.format(item + 1001) for item in numbers] 

The use of a custom checkmark format is too large here, so I will leave it for now. However, it is very convenient in the right situation.

+2
source

All Articles