Home > Mobile >  To scale diagram in python
To scale diagram in python

Time:10-12

So I need to create a to scale diagram with python when it is printed on a sheet of paper. E.g. the distance is plotted at the x-axis and 1 meter is equivalent to 1 cm when it is measured with a square (1:100). Does anyone have a simple solution for that with matplotlib or anything else?

In Matlab I would do something like this:

xmin = 1420;
xmax = 1500;
ymin = 0;
ymax = 90;
step_x = 10;
step_y = 10;
width = 16; 
height = 9;

axis([xmin xmax ymin ymax]);
grid on;                                           

% scale
mx = (abs(xmax-xmin))/width;
my = (abs(ymax-ymin))/height;

% papersize 
hf=gcf;
set(hf,'PaperUnits','centimeters');
set(hf,'PaperType','A4');
set(hf,'PaperOrientation','landscape');
set(hf,'paperposition',[1.0 6.0 28 18]);  
set(hf,'Position',[100 100 1065 675]);

% axis
ha=gca;
set(ha,'units','centimeters');
set(ha,'position',[2.5 4.5 width height]);
set(ha,'xTick',(xmin:step_x:xmax));
set(ha,'yTick',(ymin:step_y:ymax));

enter image description here

CodePudding user response:

You can set the size of the figure (note: in inches) and the plotting area (note: in fractions of hight/width) as follows:

from matplotlib import pyplot as plt

fig = plt.figure(figsize=(paper_width, paper_height)) #in inches
ax = fig.add_axes((left_margin, bottom_margin, plot_width, plot_height)) #in fraction of hight/width

Applying it to your example, the code could look as follows:

from matplotlib import pyplot as plt

#conversion factor centimeters to inches, as mpl uses inches only
cm = 1/2.54

#plot data settings
xmin = 1420 #[U/min]
xmax = 1500 #[U/min]
step_x = 10 #[U/min]
ymin = 0 #[%]
ymax = 90 #[%]
step_y = 10 #[%]

#paper settings
paper_width = 28.7 #[cm]
paper_height = 21 #[cm]
left_margin = 3.5 #[cm] sample margin
bottom_margin = 4.5 #[cm] sample margin

#figure settings
figure_width = (xmax-xmin)/step_x*2 #[cm] -> 2cm per 10U/min
figure_height = (ymax-ymin)/step_y #[cm] -> 1cm per 10%
left = left_margin / paper_width #[%] from width
bottom = bottom_margin / paper_height #[%] from height
width  = figure_width / paper_width #[%] from width
height = figure_height / paper_height #[%] from height

#define figure
fig = plt.figure(figsize=(paper_width*cm, paper_height*cm))
ax = fig.add_axes((left, bottom, width, height))

#set axis limits
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
ax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(step_x))
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(step_y))

#use grid (optionally use light gray)
ax.grid(which='both', color='#DDDDDD', linewidth=0.8)

#define some sample plot
ax.plot([1, 2, 3], label=r'$\eta = f(n)$')
ax.legend()
plt.xlabel('Läuferdrehzahl in U/min')
plt.ylabel(r'$\eta$ in %')
plt.show()

#save the data
fig.savefig('test.png', papertype = 'a4', orientation = 'landscape', dpi=100)
fig.savefig('test.pdf', papertype = 'a4', orientation = 'landscape', dpi=100)
  • Related