Search code examples
pythonmatplotlibgridlines

How to add vertical tick marks to all horizontal grid lines in matplotlib?


I would like to know if it is possible to have the x-ticks (major and minor) displayed on all horizontal grid lines of a matplotlib graph.

I have a large line graph with many mostly vertical lines (see image). I use horizontal grid lines because they do not interfere with the data. But I do not want to use vertical grid lines because the graph is already quite busy.

What I would like is to have major and minor vertical tick marks shown on every horizontal grid line (as if I had shown all vertical grid lines, but erased everywhere that wasn't crossing a horizontal grid line).

Is this possible?

Here is a sample image that needs the vertical ticks added to every grey horizontal grid line.

Sample train string line diagram


Solution

  • There's no easy function that will do this for you.

    One possible solution is to plot vertical lines using vlines at the points where the xticks are, using the y ticks location as the maximum y value and subtracting a small offset for the y minimum. A simple example:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    ax.plot([1,2,3], [1,2,3])
    ax.set_yticks([1, 2, 2.5])
    ax.set_xticks([1, 1.5, 2, 2.5, 3])
    ax.grid(axis="y")
    
    yticks = ax.get_yticks()
    xticks = ax.get_xticks()
    
    for ytick in yticks:
        for xtick in xticks:
            ax.vlines(xtick, ytick-0.05, ytick, linewidth=0.5)
    
    plt.show()
    

    enter image description here