如何使用matplotlib指定以mm / cm为单位的图的边距?

时间:2011-11-04 08:58:28

标签: plot matplotlib axis margin

实施例

假设我有两个三角形:

  • 具有点(0,0),(10,0),(10,0.5)和
  • 的三角形
  • 具有点(0,0),(1,0),(0.5,11)
  • 的三角形

生成的两个图表未指定xlimylim,如下所示: enter image description here

问题

我需要做些什么来满足下面列出的所有点?

  • 使三角形可见,这样三角线就不会被轴隐藏
  • 为所有绘图指定相同边距,单位为mm,cm或其他单位 (在上面的例子中,只使用了两个三角形。实际上我有n个三角形。)
    边距是指三角形的外部点与轴之间的距离。

结果图应如下所示 enter image description here 不同的是,用红色箭头标记的距离全部应该是相同的!

2 个答案:

答案 0 :(得分:0)

我不知道以cm / mm为单位的方法,但你可以用总大小的百分比来做到这一点:

# you don't really need this see bellow
#from matplotlib.backends.backend_pdf import PdfPages
import pylab
import matplotlib.pyplot as plt

left,bottom,width,height = 0.2,0.1,0.6,0.6 # margins as % of canvas size 

fig = plt.figure(figsize=(4,4),facecolor="yellow") # figure size in Inches
fig.patch.set_alpha(0.8) # just a trick so you can see the difference 
                         # between the "canvas" and the axes
ax1 = plt.Axes(fig,[left,bottom,width,height])
ax1.plot([1,2,3,4],'b') # plot on the first axes you created
fig.add_axes(ax1)

ax1.plot([0,1,1,0,0], [0,0,1,1,0],"ro") # plot on the first axes you created
ax1.set_xlim([-1.1,2]) 
ax1.set_ylim([-1.1,2]) 

# pylab.plot([0,1,1,0,0], [0,0,1,1,0],"ro") avoid usig if you 
# want to control more frames in a plot
# see my answer here
#http://stackoverflow.com/questions/8176458/\
#remove-top-and-right-axis-in-matplotlib-after-\
#increasing-margins/8180844#8180844

# pdf = PdfPages("Test.pdf")# you don't really need this
# pylab.savefig(pdf, papertype = "a4", format = "pdf")
# automagically make your pdf like this
pylab.savefig("Test1.pdf", papertype="a4",facecolor='y')  
pylab.show()
pylab.close()       
# pdf.close()

,输出为:

image with margins

corrected image

更正后的图片:

答案 1 :(得分:0)

你的两个带点(0,0),(10,0),(10,0.5)和(0,0),(1,0),(0.5,11)的三角形将在pylab中表示为:

Ax = [0, 10, 10]
Ay = [0, 0, 0.5]
Bx = [0, 1, 0.5]
By = [0, 0, 11]

pylab.plot(Ax, Ay)
pylab.plot(Bx, By)

让我们看看最低X值是什么:

lowestX = None

for x in Ax+Bx:
    if lowestX==None or x<lowestX:
        lowestX = x

让读者为highestXlowestYhighestY执行相同操作。

现在,考虑2个单位的边界,您可以从最低和最高值添加/减去这些单位,并设置xlimylim

margin = 2

pylab.xlim([lowestX-margin, highestX+margin])
pylab.ylim([lowestY-margin, highestY+margin])