2

Dear fellow Python users,

I try to produce colormaps by combining LinearSegmentedColormap in combination with Imshow, using matplotlib library, and I'm having a hard time with the actual colorbar.

The colorbar does not behaves the way I want by default, that is, it is much too big for my graph. By default, I get this:

default colorbar

So, I used the following code lines to fix colorbar height, in reference to this post:

ax = plt.gca()
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(img2, cax=cax)

An then I got this very strange result:

fixed graph

I'm not able to figure out why the added code lines interact with my axis and plot titles... Why do they go with the colorbar?

Here is the complete code:

import matplotlib.pyplot as plt
import matplotlib.pylab  as pylab
import matplotlib.colors as colors
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable       

#random data for example
clmap = np.random.rand(30,500)

#plot 2D color map
fig = plt.figure()
cmap2 = colors.LinearSegmentedColormap.from_list('my_colormap', ['blue','green','red'], 256)
img2 = plt.imshow(clmap,interpolation='nearest',cmap = cmap2,origin='lower')
ax = plt.gca()
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
fig.colorbar(img2, cmap = cmap2, cax=cax)
plt.title('color map of atom probab at iteration 1')
plt.xlabel('atom id')
plt.ylabel('layer')
fig.savefig("map_p_1.png")
plt.gcf().clear()
Community
  • 1
  • 1
Glxblt76
  • 365
  • 5
  • 14

1 Answers1

1

You're mixing the pyplot state machine (plt) with the object oriented API.
After creating the second axes object (cax), it will be the current axes. All pyplot commands comming afterwards are applied to this axes.

The easiest way out is to apply the pyplot commands before creating the new axes:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable       

#random data for example
clmap = np.random.rand(30,500)

#plot 2D color map
fig = plt.figure()
plt.title('color map of atom probab at iteration 1')
plt.xlabel('atom id')
plt.ylabel('layer')
cmap2 = colors.LinearSegmentedColormap.from_list('my_colormap', ['blue','green','red'], 256)
img2 = plt.imshow(clmap,interpolation='nearest',cmap = cmap2,origin='lower')
ax = plt.gca()
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
fig.colorbar(img2, cmap = cmap2, cax=cax)

fig.savefig("map_p_1.png")

plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712