How to determine PlotRange to include all of graphics?

前端 未结 3 720
后悔当初
后悔当初 2020-12-13 09:25

Given Graphics object, how do I determine the range of coordinates needed to include all of graphics? Basically I need something like what Show doe

3条回答
  •  渐次进展
    2020-12-13 10:16

    I can suggest the following Ticks hack:

    pl = Plot[Sin[x], {x, 0, 10}];
    Reap[Rasterize[Show[pl, Ticks -> {Sow[{##}] &, Sow[{##}] &}, ImageSize -> 0], 
       ImageResolution -> 1]][[2, 1]]
    
    => {{-0.208333, 10.2083}, {-1.04167, 1.04167}} 
    

    The trick is that real PlotRange is determined by the FrontEnd, not by the Kernel. So we must force the FrontEnd to render the graphics in order to get tick functions evaluated. This hack gives the complete PlotRange with explicit value of PlotRangePadding added.

    More general solution taking into account a possibility that pl has non-standard value of DisplayFinction option and that it may have Axes option set to False:

    completePlotRange[plot:(_Graphics|_Graphics3D|_Graph)] := 
     Quiet@Last@
       Last@Reap[
         Rasterize[
          Show[plot, Axes -> True, Frame -> False, Ticks -> (Sow[{##}] &), 
           DisplayFunction -> Identity, ImageSize -> 0], ImageResolution -> 1]]
    

    One can get the exact PlotRange (without the PlotRangePadding added) with the following function:

    plotRange[plot : (_Graphics | _Graphics3D | _Graph)] := 
     Quiet@Last@
       Last@Reap[
         Rasterize[
          Show[plot, PlotRangePadding -> None, Axes -> True, Frame -> False, 
           Ticks -> (Sow[{##}] &), DisplayFunction -> Identity, ImageSize -> 0], 
          ImageResolution -> 1]]
    

    P.S. On the Documentation page for PlotRange under the "More information" one can read: "AbsoluteOptions gives the actual settings for options used internally by Mathematica when the setting given is Automatic or All. " (emphasis mine). So it seems that the Documentation does not even guarantee that AbsoluteOptions will give correct values for PlotRange when it is not Automatic or All.

提交回复
热议问题