Search code examples
pythonmatplotlibgrid

Drawing a grid with a different color for each edge in python


It's all in the title. I'm trying to plot a grid in python, with a specific color for each edge. Here is a view of what I would like to obtain, made from tikz.

enter image description here

The tikz code gives me a roadmap for how to proceed in python: I just run two loops of coordinates and draw by hand the edge (x, y)--(x+1,y).

I see two ways of implementing this in python, but can't find the exact syntax/objects/packages to use (most of the time, people just call the grid functions, in which the axis can be given a color, but this is quite different):

  • is there a way to access the specific edges using the grid function ? If so, how are they indexed ?
  • or is there a way to draw by hand, the segment (0,0) to (0,1) and the segment (0,1) to (0,2) and plot them in the same graph, side by side ?

Thanks !


Solution

  • matplotlib.path can be used to draw polygons or also just a polyline following a specific path.
    See also the matplotlib Path Tutorial.

    Brief example with line segments in different colors:

    enter image description here

    Code:

    import matplotlib.pyplot as plt
    import matplotlib.path as mpath
    
    
    def draw_polyline(start_x, start_y, delta_x, delta_y, color):
        Path = mpath.Path
        path_data = [
        (Path.MOVETO, (start_x, start_y)),
        (Path.MOVETO, (start_x + delta_x, start_y + delta_y)),
        ]
        codes, verts = zip(*path_data)
        path = mpath.Path(verts, codes)
        x, y = zip(*path.vertices)
        line, = ax.plot(x, y, f'{color}-', lw=3)
    
    
    fig, ax = plt.subplots(1,1, figsize = (5,5))
    
    draw_polyline(0.1, 0.1, 0.0, 0.1, 'k')
    draw_polyline(0.1, 0.2, 0.1, 0.0, 'g')
    draw_polyline(0.2, 0.2, 0.0, 0.1, 'r')
    draw_polyline(0.2, 0.3, -0.1, 0.0, 'y')
    
    plt.show()
    

    Notes:

    • The first MOVETO sets the starting point, an explicit endpoint isn't required.
    • lw is linewidth
    • for sure the draw_polyline function and it's calls may need to be adapted to your data (seems like a lot of lines and maybe the coloring follows a specific function...), but the code should show the principle of using path for this

    Concerning using the grid I'd doubt that the 'segments' can be separated (but maybe others know a way).

    Matplotlib: Change color of individual grid lines shows a way to color individual grid lines, but 'only' the whole line at once and not in segments.