在matplotlib中设置使用plt.subplots创建的图形的高度和宽度? [英] Set height and width of figure created with plt.subplots in matplotlib?
本文介绍了在matplotlib中设置使用plt.subplots创建的图形的高度和宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在matplotlib中,我知道如何设置图形的高度和宽度以及DPI:
In matplotlib, I know how to set the height and width and DPI of a figure:
fig = plt.figure(figsize=(4, 5), dpi=100)
但是,如果我想创建多个小图,就无法创建这样的图形,必须使用以下方法:
However, it seems that if I want to create small multiple plots, I can't create a figure like this, I have to use this:
fig, subplots = plt.subplots(nrows=4, ncols=4)
如何设置用此类子图创建的图形的高度,宽度和DPI?
How can I set the height and width and DPI of a figure created with subplots like this?
推荐答案
gridspec 的一个工作示例模块:
A working example of the gridspec module:
import matplotlib.pyplot as plt
from matplotlib import gridspec
fig = plt.figure(figsize=(18,18))
gs = gridspec.GridSpec(3, 3)
ax1 = fig.add_subplot(gs[0,:])
ax1.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')
ax2 = fig.add_subplot(gs[1,:-1])
ax2.plot([1,2,3,4], [1,4,9,16], 'k-')
ax3 = fig.add_subplot(gs[1:, 2])
ax3.plot([1,2,3,4], [1,10,100,1000], 'b-')
ax4 = fig.add_subplot(gs[2,0])
ax4.plot([1,2,3,4], [0,0,1,1], 'g-')
ax5 = fig.add_subplot(gs[2,1])
ax5.plot([1,2,3,4], [1,0,0,1], 'c-')
gs.update(wspace=0.5, hspace=0.5)
plt.show()
但我更喜欢将它包装在一个函数中并像这样使用它:
But I prefer wrapping it in a function and using it like this:
def mySubplotFunction(fig,gs,x,y,c,ax=None):
if not ax:
ax = fig.add_subplot(gs)
ax.plot(x, y, c)
return fig, ax
用法:
fig2 = plt.figure(figsize=(9,9))
fig2, ax1 = mySubplotFunction(fig2,gs[0,:],[1,2,3,4,5],[10,5,10,5,10],'r-');
fig2, ax2 = mySubplotFunction(fig2,gs[1,:-1],[1,2,3,4],[1,4,9,16],'k-');
这篇关于在matplotlib中设置使用plt.subplots创建的图形的高度和宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文