如何用Python绘制可打印的等比例示意图(附Matlab参考示例)
用Python创建可打印的等比例示意图
我需要用Python创建一张可打印在纸张上的等比例示意图,例如将距离绘制在x轴上,打印后用尺子测量时1米对应1厘米(比例为1:100)。请问是否有基于matplotlib或其他工具的简易实现方案?
以下是我在Matlab中的实现代码:
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));
示例效果:带有网格、刻度清晰的横向A4示意图,X轴范围1420-1500,Y轴覆盖0-90区间。
基于Matplotlib的实现方案
用Matplotlib可以轻松实现这种等比例可打印示意图,核心是精准控制纸张尺寸、坐标轴物理位置和数据比例,确保打印后物理测量尺寸与数据尺寸符合设定比例。以下是对应你Matlab代码的Python实现:
import matplotlib.pyplot as plt # 数据范围与刻度配置 xmin = 1420 xmax = 1500 ymin = 0 ymax = 90 step_x = 10 step_y = 10 # 坐标轴的物理尺寸(单位:厘米) axis_width = 16 axis_height = 9 # 创建画布,设置A4横向尺寸(A4纸为29.7cm×21cm,转成Matplotlib默认的英寸单位) fig = plt.figure(figsize=(29.7/2.54, 21/2.54), dpi=100) # 设置打印边距,对应Matlab的paperposition参数(左、底、右、上相对纸张的比例) fig.subplots_adjust(left=1/29.7, bottom=6/21, right=(1+28)/29.7, top=(6+18)/21) # 创建坐标轴,指定其在纸张上的相对位置与物理尺寸 ax = fig.add_axes([2.5/29.7, 4.5/21, axis_width/29.7, axis_height/21]) # 设置坐标轴的数据范围 ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) # 设置刻度间隔 ax.set_xticks(range(xmin, xmax+1, step_x)) ax.set_yticks(range(ymin, ymax+1, step_y)) # 显示网格 ax.grid(True) # 计算并输出比例(用于验证) scale_x = (xmax - xmin) / axis_width scale_y = (ymax - ymin) / axis_height print(f"X轴比例:1厘米对应{scale_x}单位数据") print(f"Y轴比例:1厘米对应{scale_y}单位数据") # 保存为无失真的可打印文件(优先选PDF矢量格式) plt.savefig("scale_diagram.pdf", dpi=300) plt.show()
核心要点:
- 单位适配:Matplotlib默认用英寸,因此将厘米尺寸除以2.54转换为英寸,或直接用相对比例(坐标轴尺寸/纸张尺寸)配置,避免单位转换误差。
- 比例控制:通过数据范围与坐标轴物理尺寸的比值固定比例,比如要实现1:100(1厘米对应1米),只需保证
(数据范围)/(坐标轴物理厘米数)=100即可。 - 输出格式:推荐保存为PDF格式,矢量图打印无失真;若用PNG,需设置300DPI以上的分辨率保证清晰度。
内容的提问来源于stack exchange,提问作者Horst-Jackson
相关产品推荐
相关产品推荐

