Using matplotlib, how can I print something “actual size”?

后端 未结 3 1116
孤城傲影
孤城傲影 2021-01-03 02:09

I have a number of plots where the x- and y-axes are in centimeter units, and I am already using axis(\'equal\') to ensure proper aspect ratios. I would like to print out th

3条回答
  •  长发绾君心
    2021-01-03 02:21

    Consider this example. Where I specify exactly the dimension of my axes in cm. matplotlib works in inches, so I convert to inches. And then I also save it with a particular dpi (128) so that it matches the designed dimensions in my display. This of course varies for every display. I found that by trial and error, even though there might be other methods. Well here the code:

    left_margin = 1.   # cm
    right_margin = 1.  # cm
    figure_width = 10. # cm
    figure_height = 7. # cm
    top_margin = 1.    # cm
    bottom_margin = 1. # cm
    
    box_width = left_margin + figure_width + right_margin   # cm
    box_height = top_margin + figure_height + bottom_margin # cm
    
    cm2inch = 1/2.54 # inch per cm
    
    # specifying the width and the height of the box in inches
    fig = figure(figsize=(box_width*cm2inch,box_height*cm2inch))
    ax = fig.add_subplot(111)
    ax.plot([1,2,3])
    
    fig.subplots_adjust(left   = left_margin / box_width,
                        bottom = bottom_margin / box_height,
                        right  = 1. - right_margin / box_width,
                        top    = 1. - top_margin   / box_height,
                        )
    fig.savefig('ten_x_seven_cm.png', dpi=128)
    # dpi = 128 is what works in my display for matching the designed dimensions.
    

提交回复
热议问题