Set graphics in colorbar in matplotlib

I have an imshow graph that shows colobar for numeric values. The color bar is much larger than the graph. Is there a way to scale them, so they have the same size, preferably without affecting the aspect ratio of the graph?

grid = np.ma.array(grid, mask=np.isnan(grid)) plot.imshow(grid, interpolation='nearest', aspect='equal', vmax = private.vmax, vmin = private.vmin) plot.minorticks_off() plot.set_xticks(range(len(placex))) plot.set_yticks(range(len(placey))) plot.set_xticklabels(placex) plot.set_yticklabels(placey, rotation = 0) plot.colorbar() plot.show() 
+4
source share
1 answer

You can specify the axis object with any of the matplotlib built-in methods, and then use it for your color bar, for example:

 import matplotlib.pyplot as plt import numpy as np ax2 = plt.subplot2grid((1,6), (0, 5), colspan=1) ax1 = plt.subplot2grid((1,6), (0, 0), colspan=5) plt.imshow(np.random.random((10,10))) plt.colorbar(cax=ax2) plt.show() 

This will result in something like:

Plot of sample code

Although this will not help if your imshow axes become very flat (due to aspect = "equal", this may happen).

If you want to handle such cases, you can

  • Adjust the size of the shape to an aspect of your mesh, for example.

    fig = figure (figsize = grid.shape [1] * 1.5 / dpi, grid.shape [0] / dpi)

  • Read the coordinates of ax1 AFTER plotting, create ax2 immediately after that with the coordinates converted correctly, and then use ax2 for the color bar. This does not behave well when you resize the window, but can work if you simply create graphics as image files automatically.

If 2. what you need, I can add an example for this, but I will only do this work if you are sure that this is what you need.

Hi Torsten

+4
source

All Articles