TransWikia.com

How can I draw a graph with squares as in the diagram below

TeX - LaTeX Asked on March 11, 2021

I want to draw a graph with small square boxes
enter image description here

One Answer

Since the linked example is only for TiKZ, here is a simple way to add graph paper to any Metapost graph.

enter image description here

This was produced using the following source, compiled with lualatex:

documentclass[border=5mm]{standalone}
usepackage{luamplib}
begin{document}
mplibtextextlabel{enable}
begin{mplibcode}
input graphpaper
beginfig(1);

    path xx, yy, ff;

    xx = 42 left -- 377 right;
    yy = 21 down -- 233 up;


    ff = (20, 20) {right} .. (300, 200) {dir 10};

    drawarrow xx;
    drawarrow yy;

    draw ff withcolor 2/3 red;

    add_background_grid(1cm, 3/4 white);
    add_background_grid(1mm, 7/8 white); 

endfig;
end{mplibcode}
end{document}

The add_background_grid macro is defined like this:

vardef add_background_grid(expr s, c) = 
    save B, C;
    path B; B = bbox currentpicture;
    picture C; C = currentpicture;
    currentpicture := nullpicture;

    for x = s step s until floor xpart urcorner B:
        draw (x, ceiling ypart llcorner B) -- (x, floor ypart urcorner B) withcolor c;
    endfor
    for x = 0 step -s until ceiling xpart llcorner B:
        draw (x, ceiling ypart llcorner B) -- (x, floor ypart urcorner B) withcolor c;
    endfor
    for y = s step s until floor ypart urcorner B:
        draw (ceiling xpart llcorner B, y) -- (floor xpart urcorner B, y) withcolor c;
    endfor
    for y = 0 step -s until ceiling ypart llcorner B:
        draw (ceiling xpart llcorner B, y) -- (floor xpart urcorner B, y) withcolor c;
    endfor
    draw C;
enddef;

which I had saved as graphpaper.mp and included using the input graphpaper line at the top of the first example.

This works by measuring the size of the bounding box of the current picture; erasing the current picture; drawing a grid (from the origin); and then drawing the saved copy of the original picture back on top.

Answered by Thruston on March 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP