Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I am trying to figure out how to align different types of plots into one image. For example in the following code, it plots two lines on top of a MatrixPlot. I want the lines to pass through the corners of the red squares in the overlaid image.

 Overlay[{
     MatrixPlot[Table[Mod[i^2 + j^2, 3], {i, 20}, {j, 20}], 
         ColorRules -> {0 -> Red, 1 -> White, 2 -> White}, AspectRatio -> Full],
     Plot[{y = x, y = -x/1 + 1}, {x, 0, 1}, AspectRatio -> Full]}, 
     ImageSize -> Full]

How can I create the image so the lines and squares fit together better?

share|improve this question
add comment

2 Answers 2

up vote 3 down vote accepted

When you overlay two plots like that, you need to make sure that both plots have the same AspectRatio, PlotRangePadding and ImagePadding. It also improves the clarity if you turn off the ticks for one of the plots:

With[{opts = {AspectRatio -> 1, PlotRangePadding -> 0, ImagePadding -> 18}}, 
    Overlay[{
        MatrixPlot[Table[Mod[i^2 + j^2, 3], {i, 20}, {j, 20}], 
            ColorRules -> {0 -> Red, 1 -> White, 2 -> White}, opts, FrameTicks -> False], 
        Plot[{y = x, y = -x/1 + 1}, {x, 0, 1}, opts]}, ImageSize -> Full
    ]
]

I've eyeballed the ImagePadding here, and you will have to adjust it if you change the font size or include frame labels. You can also use different paddings for each side.

For a more robust and automated solution, you can use this answer by Heike to retrieve the image padding of both plots and set them both to the maximum padding as I did in this answer.

share|improve this answer
    
Sweet! Thank you @rm -rf ! –  spaceKnot Jan 4 at 0:59
add comment

You also could just place them in the same coordinate system. That opens few other ways.

MatrixPlot[Table[Mod[i^2 + j^2, 3], {i, 20}, {j, 20}], 
 ColorRules -> {0 -> Red, 1 -> White, 2 -> White},
 AspectRatio -> 1, PlotRangePadding -> 0, Epilog -> {
   {Orange, Line[{{0, 0}, {20, 20}}]},
   {Green, Line[{{0, 20}, {20, 0}}]}}]

or...

Show[
 MatrixPlot[Table[Mod[i^2 + j^2, 3], {i, 20}, {j, 20}], 
  ColorRules -> {0 -> Red, 1 -> White, 2 -> White}],
 Plot[{y = x, y = 20 - x}, {x, 0, 20}],
 AspectRatio -> 1, PlotRangePadding -> 0]

...

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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