Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axes class - set explicitly size (width/height) of axes in given units

I want to to create a figure using matplotlib where I can explicitly specify the size of the axes, i.e. I want to set the width and height of the axes bbox.

I have looked around all over and I cannot find a solution for this. What I typically find is how to adjust the size of the complete Figure (including ticks and labels), for example using fig, ax = plt.subplots(figsize=(w, h))

This is very important for me as I want to have a 1:1 scale of the axes, i.e. 1 unit in paper is equal to 1 unit in reality. For example, if xrange is 0 to 10 with major tick = 1 and x axis is 10cm, then 1 major tick = 1cm. I will save this figure as pdf to import it to a latex document.

This question brought up a similar topic but the answer does not solve my problem (using plt.gca().set_aspect('equal', adjustable='box') code)

From this other question I see that it is possible to get the axes size, but not how to modify them explicitly.

Any ideas how I can set the axes box size and not just the figure size. The figure size should adapt to the axes size.

Thanks!

For those familiar with pgfplots in latex, it will like to have something similar to the scale only axis option (see here for example).

like image 202
Gabriel Avatar asked Jul 07 '17 11:07

Gabriel


People also ask

How do you change the size of an AXE in Python?

To change the range of X and Y axes, we can use xlim() and ylim() methods.

What does PLT axis () do?

The plt. axis() method allows you to set the x and y limits with a single call, by passing a list which specifies [xmin, xmax, ymin, ymax] : In [11]: plt.


2 Answers

The axes size is determined by the figure size and the figure spacings, which can be set using figure.subplots_adjust(). In reverse this means that you can set the axes size by setting the figure size taking into acount the figure spacings:

import matplotlib.pyplot as plt  def set_size(w,h, ax=None):     """ w, h: width, height in inches """     if not ax: ax=plt.gca()     l = ax.figure.subplotpars.left     r = ax.figure.subplotpars.right     t = ax.figure.subplotpars.top     b = ax.figure.subplotpars.bottom     figw = float(w)/(r-l)     figh = float(h)/(t-b)     ax.figure.set_size_inches(figw, figh)  fig, ax=plt.subplots()  ax.plot([1,3,2])  set_size(5,5)  plt.show() 
like image 76
ImportanceOfBeingErnest Avatar answered Sep 28 '22 03:09

ImportanceOfBeingErnest


It appears that Matplotlib has helper classes that allow you to define axes with a fixed size Demo fixed size axes

like image 28
Max Avatar answered Sep 28 '22 01:09

Max