Issue
I would please like suggestions for how to override the default matplotlib behaviour when plotting images as subplots, whereby the subplot sizes don't seem to match the figure size. I would like to set my figure size (e.g. to match the width of an A4 page) and have the subplots automatically stretch to fill the space available. In the following example, the code below gives a figure with a lot of white space between the panels:
import numpy as np
import matplotlib.pyplot as plt
data=np.random.rand(10,4)
#creating a wide figure with 2 subplots in 1 row
fig,ax=plt.subplots(1,2, figsize=(9,3))
ax=ax.reshape(1,len(ax))
for i in [0,1]:
plt.sca(ax[0,i])
plt.imshow(data,interpolation='nearest')
plt.colorbar()
I would like the subplots to be stretched horizontally so that they fill the figure space. I will make many similar plots with different numbers of values along each axis, and the space between the plots appears to depend on the ratio of x values to y values, so I would please like to know if there is a good general way to set the subplot widths to fill the space. Can the physical size of subplots be specified somehow? I've been searching for solutions for a few hours, so thanks in advance for any help you can give.
Solution
First, you're using calls to plt
when you have Axes
objects as your disposal. That road leads to pain. Second, imshow
sets the aspect ratio of the axes scales to 1. That's why the axes are so narrow. Knowing all that, your example becomes:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(10,4)
#creating a wide figure with 2 subplots in 1 row
fig, axes = plt.subplots(1, 2, figsize=(9,3))
for ax in axes.flatten(): # flatten in case you have a second row at some point
img = ax.imshow(data, interpolation='nearest')
ax.set_aspect('auto')
plt.colorbar(img)
On my system, that looks like this:
Answered By - Paul H
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.