Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change values on matplotlib imshow() graph axis

Say I have some input data:

data = np.random.normal(loc=100,scale=10,size=(500,1,32)) hist = np.ones((32,20)) # initialise hist for z in range(32):     hist[z],edges = np.histogram(data[:,0,z],bins=np.arange(80,122,2)) 

I can plot it using imshow():

plt.imshow(hist,cmap='Reds') 

getting:

enter image description here

However, the x-axis values do not match the input data (i.e. mean of 100, range from 80 to 122). Therefore, I'd like to change the x-axis to show the values in edges.

I have tried:

ax = plt.gca() ax.set_xlabel([80,122]) # range of values in edges ... # this shifts the plot so that nothing is visible 

and

ax.set_xticklabels(edges) ... # this labels the axis but does not centre around the mean: 

enter image description here

Any ideas on how I can change the axis values to reflect the input data I am using?

like image 561
atomh33ls Avatar asked Sep 09 '13 10:09

atomh33ls


People also ask

How do I change axis labels in Pyplot?

To set labels on the x-axis and y-axis, use the plt. xlabel() and plt. ylabel() methods.

How do you flip the Y axis in Imshow?

Use ax. invert_yaxis() to invert the y-axis, or ax. invert_xaxis() to invert the x-axis.


1 Answers

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))  ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0]) ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio 

enter image description here

like image 127
Rutger Kassies Avatar answered Oct 02 '22 00:10

Rutger Kassies