Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying axes on matplotlib colorbar plot of 2D array

I have a 2D numpy array that I want to plot in a colorbar. I am having trouble changing the axis so that they display my dataset. The vertical axis goes 'down' from 0 to 100, whereas I want it to go 'up' from 0.0 to 0.1. So I need to do two things:

  • Flip the array using np.flipud() and then 'flip' the axis as well
  • Change the labels to go from 0.0 to 0.1, instead of 0 to 100

Here is an example of what my colorbar plot currently looks like: Example of Colorbar plot

And here is the code:

data = np.load('scorr.npy')
(x,y) = np.unravel_index(data.argmax(), data.shape)
max=data[x][y]

fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.imshow(data, interpolation='nearest')
cbar = fig.colorbar(cax, ticks=[-max, 0, max])
cbar.ax.set_yticklabels([str(-max), '0', str(max)])
plt.show()

Does anybody have any suggestions? Thanks in advance!

like image 808
Doa Avatar asked Jun 07 '11 14:06

Doa


People also ask

How do you change the axis of a plot in MatPlotLib?

To change the range of X and Y axes, we can use xlim() and ylim() methods.

How do I change the y-axis values in MatPlotLib?

To specify the value of axes, create a list of characters. Use xticks and yticks method to specify the ticks on the axes with x and y ticks data points respectively. Plot the line using x and y, color=red, using plot() method. Make x and y margin 0.

How do I move Y-axis in MatPlotLib?

MatPlotLib with Python Create a figure using the figure() method. Using the above figure method, create the axis of the plot, using add_subplot(xyz), where x is row, y is column, and z is index. To shift the Y-axis ticks from left to right, use ax. yaxis.

How do I change the color bar in MatPlotLib?

You can change the color of bars in a barplot using color argument. RGB is a way of making colors. You have to to provide an amount of red, green, blue, and the transparency value to the color argument and it returns a color.


1 Answers

You want to look at the imshow options "origin" and "extent", I think.

import matplotlib.pyplot as plt
import numpy as np

x,y = np.mgrid[-2:2:0.1, -2:2:0.1]
data = np.sin(x)*(y+1.05**(x*np.floor(y))) + 1/(abs(x-y)+0.01)*0.03

fig = plt.figure()
ax = fig.add_subplot(111)
ticks_at = [-abs(data).max(), 0, abs(data).max()]
cax = ax.imshow(data, interpolation='nearest', 
                origin='lower', extent=[0.0, 0.1, 0.0, 0.1],
                vmin=ticks_at[0], vmax=ticks_at[-1])
cbar = fig.colorbar(cax,ticks=ticks_at,format='%1.2g')
fig.savefig('out.png')

extent and origin

like image 169
DSM Avatar answered Oct 15 '22 02:10

DSM