How to specify the border of a plot in mm / cm using matplotlib?

Example

Suppose I have two triangles:

  • Triangle with points (0, 0), (10, 0), (10, 0.5) and
  • triangle with points (0, 0), (1, 0), (0,5, 11)

The resulting two graphs without specifying xlim and ylim are as follows: enter image description here

Question

What do I need to do to satisfy all the points listed below?

  • Make the triangle visible so that no line of the triangle is hidden by the axis
  • Indicate the same field for all graphs in mm, cm or another block.
    (in the above example, only two triangles were used. In fact, I have n triangles).

    By field, I mean the distance between the external points of the triangle and the axis.

The resulting graphs should look like this: enter image description here with the difference that the distances marked with red arrows should all be the same!

+4
source share
2 answers

I do not know how to do this in cm / mm, but you can do it with a preliminary value of the total size:

 # 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() 

and output:

image with margins

corrected image

corrected image:

0
source

Your two triangles with points (0, 0), (10, 0), (10, 0.5) and (0, 0), (1, 0), (0.5, 11) will be represented in pylab as:

 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) 

Let's see what the lowest value of X is:

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

An exercise for the reader to do the same for highestX , lowestY and highestY .

Now consider the border of 2 units, you can add / subtract these units from the lowest and highest values โ€‹โ€‹and set xlim and ylim :

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

Source: https://habr.com/ru/post/1379610/


All Articles