简体   繁体   中英

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?

The aspect ratio is set to "equal" for the 5 imshow() calls (check by calling ax1.get_aspect() ) while for ax5 it is set to auto which gives you the non-square shape you observe. I'm guessing which gives you the non-square shape you observe. I'm guessing imshow()` defaults to equal while plot does not.

To fix this set all the axis aspect ratios manually eg 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(..)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM