Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with python matplotlib and subplot sizes

I am trying to create a figure with 6 sub-plots in python but I am having a problem. Here is a simplified version of my code:

import matplotlib.pyplot as plt
import numpy

g_width = 200
g_height = 200
data = numpy.zeros(g_width*g_height).reshape(g_height,g_width)

ax1 = plt.subplot(231)
im1 = ax1.imshow(data)
ax2 = plt.subplot(232)
im2 = ax2.imshow(data)
ax3 = plt.subplot(233)
im3 = ax3.imshow(data)
ax0 = plt.subplot(234)
im0 = ax0.imshow(data)
ax4 = plt.subplot(235)
im4 = ax4.imshow(data)
ax5 = plt.subplot(236)
ax5.plot([1,2], [1,2])
plt.show()

The above figure has 5 "imshow-based" sub-plots and one simple-data-based sub-plot. Can someone explain to me why the box of the last sub-plot does not have the same size with the other sub-plots? If I replace the last sub-plot with an "imshow-based" sub-plot the problem disappears. Why is this happening? How can I fix it?

like image 478
AstrOne Avatar asked Jul 26 '26 21:07

AstrOne


1 Answers

The aspect ratio is set to "equal" for the 5imshow()calls (check by callingax1.get_aspect()) while forax5it is set toautowhich gives you the non-square shape you observe. I'm guessingimshow()` defaults to equal while plot does not.

To fix this set all the axis aspect ratios manually e.g when creating the plot ax5 = plt.subplot(236, aspect="equal")

On a side node if your creating many axis like this you may find this useful:

fig, ax = plt.subplots(ncols=3, nrows=2, subplot_kw={'aspect':'equal'})

Then ax is a tuple (in this case ax = ((ax1, ax2, ax3), (ax4, ax5, ax6))) so to plot in the i, j plot just call

ax[i,j].plot(..)
like image 110
Greg Avatar answered Jul 29 '26 10:07

Greg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!