How to align the output of MatrixPlot with the output of Plot

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?

-

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.

-
Sweet! Thank you @rm -rf ! – spaceKnot Jan 4 '14 at 0:59

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]


...

-