Search code examples
pythonmatplotlibgridlines

Configuring grid-lines


Consider the figure below.

enter image description here

This image has been set up with the following code.

  plt.rc('text', usetex=True)
  plt.rc('font', family='serif')
  fig, ax = plt.subplots()
  
  ax.set_xlabel("Run Number", fontsize=25)
  
  plt.grid(True, linestyle='--')
  plt.tick_params(labelsize=20)
  ax.set_xticklabels(map(str,range(number_of_runs)))
  ax.minorticks_on()

  ax.set_ylim([0.75,1.75])

I have not included the code that actually generates the data for plotting for the sake of clarity.

Unlike the diagram above, I would like to draw grid-lines perpendicular to the X-axis through each orange (and hence blue) dot. How do I do this? The x-coordinates of the successive orange and blue dots form the same arithmetic progression in my code.

Also I notice that the tick numbers numbered 1,2,... are wrong for my application. Instead, I would like each successive grid-line, which I ask for as perpendicular to the X-axis in the previous step, to be numbered sequentially from 1 along the X-axis. How do I configure the Xtick marks for this?


Solution

  • The grid lines cross the xticks (or yticks). You need to define xticks properly so that the grid lines cross your data points (the dots)

    example below:

    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    number_of_runs = range(1,10)    # use your actual number_of_runs
    ax.set_xticks(number_of_runs, minor=False)
    ax.xaxis.grid(True, which='major')
    

    In case you want to have only vertical lines, add this:

    ax.yaxis.grid(False, which='major')
    

    Similar question here.