Question

I want to add a line with plot() to a color map made with imshow() in matplotlib, where several sub-figures of different sizes are assumed. When adding a line, the color map somehow changes size. How do I get around this?

Here is a simple example illustrating the problem:

import scipy.stats       as stat
import matplotlib.pyplot as plt
import matplotlib.cm     as cm
import numpy             as np

fig = plt.figure(figsize=(12, 4))
plt.axes([.05,.1,.4,.8])
data = stat.uniform.rvs(size=2400).reshape((40,60))
plt.imshow(data,cmap=cm.jet,vmin=0,vmax=1)
plt.colorbar(fraction=.03)
plt.plot(range(60),20*np.ones(60),'w-',lw=3)  #  <-- causing problems
plt.title('the damn white line')
Was it helpful?

Solution

You can avoid this with the command plt.autoscale(False) after the first plot.

Also, in my opinion, it would be a better solution to use plt.axhline rather than plt.plot to make a horizontal line, as the axhline spans the whole horizontal extent of the axes, even if you pan/zoom in the plot.

In other words, your example could be rewritten like this:

import scipy.stats       as stat
import matplotlib.pyplot as plt
import matplotlib.cm     as cm
import numpy             as np

data = stat.uniform.rvs(size=2400).reshape((40,60))

plt.figure(figsize=(12, 4))
plt.axes([.05,.1,.4,.8])
plt.imshow(data,cmap=cm.jet,vmin=0,vmax=1)
plt.colorbar(fraction=.03)
plt.autoscale(False)
plt.axhline(y=20, c='w', lw=3)
plt.title('the damn white line')

enter image description here

OTHER TIPS

Here is a very simple alternative solution: Changing the order of imshow() and plot()

import scipy.stats       as stat
import matplotlib.pyplot as plt
import matplotlib.cm     as cm
import numpy             as np

fig = plt.figure(figsize=(12, 4))
plt.axes([.05,.1,.4,.8])
data = stat.uniform.rvs(size=2400).reshape((40,60))
plt.plot(range(60),20*np.ones(60),'w-',lw=3)  #  <--- mow before imshow()
plt.imshow(data,cmap=cm.jet,vmin=0,vmax=1)
plt.colorbar(fraction=.03)
plt.title('the damn white line')

Output is the same as for nordev's answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top