0
$\begingroup$

Let's say I have two plots I want to Show on top of each other. However, I am only interested in a certain sub-region:

myplots = {Plot[x, {x, 0, 15}], Plot[1/10 x^2, {x, 0, 15}]};
Show[myplots, PlotRange -> {{2, 4}, All}]

enter image description here

I don't like two things about this plot:

1) The y axis and numbers are not displayed.

2) The y axis scale is not adjusted to display only the relevant region where the curves can be seen.

How to fix these issues?

PS: Note that I do want to display the entire region in myplots and then focus to sub-region in Show, since the plots I actually am interested in looking at take much longer to render. So having pre-rendered them completely and then selecting sub-regions in Show is a feature I'd like to keep.

$\endgroup$
1
  • 1
    $\begingroup$ You can fix the y-axis by specifying AxesOrigin -> Automatic or using FrameTicks and related options. $\endgroup$
    – Lukas Lang
    Commented Sep 16, 2017 at 19:46

1 Answer 1

1
$\begingroup$

The following works for your simple example. In general, you might need to adapt it a bit.

cropData[g_Graphics] := 
 With[
  {range = PlotRange /. Quiet@AbsoluteOptions[g]},
  g
   /. c_GraphicsComplex :> Normal@c
   /. (p : Line | Point)[pts_] :> 
    With[
     {pos = Position[
             pts,
             pt : {_, _} /; And @@ MapThread[Between, {pt, range}],
             {1}
            ][[All, 1]]
     }, 
     p[pts[[Max[Min@pos - 1, 1] ;; Min[Max@pos + 1, Length@pts]]]
    ]
  ]
 ]

It is used as

myplots = {Plot[{x}, {x, 0, 15}], Plot[1/10 x^2, {x, 0, 15}]};
cropData@Show[myplots, PlotRange -> {{2, 4}, Automatic}, AxesOrigin -> Automatic]

Mathematica graphics

As noted in the comments, you can use AxesOrigin -> Automatic to reset the axes so that they are visible in your plot.

How it works

The general idea is pretty straightforward:

  • Get the plotrange (using Quiet, as AbsoluteOptions sometimes complains for certain tick specifications, but we don't care about that)
  • Normalize all GraphicsComplexes (I'm not sure for which types of plots they are used - probably just for contour plots and similar, but this shouldn't hurt anyways)
  • Search all Line/Point primitives and filter out any point that's not inside the PlotRange. We keep one point on either side to make sure the lines go right to the edge.
  • Removing the hidden points from the plot causes the PlotRange specification to work as expected and zooms in on the y-axis
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.