1

I'm trying to do a pyplot graph but am unable to access the function family where I change the 'x tick labels'. I know the function exists but my code doesn't want to recognise it. From what I've found on the internet, I might need to move beyond using plt.plot but don't really understand why I need to do this.

Here is my code:

import matplotlib.pyplot as plt



def grapher(number_of_steps, probabilities):
    '''

    Takes the number of positions and probabilities for these posistions. Plots them
    Positions are on 1D Quantum Walk line and assumed to be a circle (?) eventually, but
    for the loops to be so long as for it to appear as a straight line for our purposes
    '''
    P = 2*(number_of_steps)+1  # Number of Positions

    positions_plot = np.arange(0,P)

    plt.style.use('seaborn-ticks')
    plt.plot(positions_plot, probabilities, marker = 'o', linestyle = "--", label = r"Probability" )
    ticks = np.arange(0,P,P//10) #Location of Ticks
    plt.xticks(ticks)
    plt.xlim(0,P)
    ax.set_xticklabels(range(-N, N+1, P // 10))

    plt.legend()
    plt.show()

And this is my error File "discretewalk.py", line 134, in grapher ax.set_xticklabels(range(-N, N+1, P // 10)) NameError: name 'ax' is not defined

jolene
  • 373
  • 2
  • 15
  • 1
    `plt.gca()` instead of `ax` perhaps. – BigBen Nov 04 '20 at 19:13
  • ax is not something defined in matplotlib, what you seen previously is most likely an axes object: try ax = plt.axes() – unlut Nov 04 '20 at 19:14
  • 2
    You probably want to read [What is the difference between drawing plots using plot, axes or figure in matplotlib?](https://stackoverflow.com/questions/37970424/what-is-the-difference-between-drawing-plots-using-plot-axes-or-figure-in-matpl) – JohanC Nov 04 '20 at 19:18

1 Answers1

0

You could either use set_xticklabels on your Axes

fig, ax = plt.subplots()
...
ax.plot(positions_plot, probabilities, marker = 'o', linestyle = "--", label = r"Probability")
...
ax.set_xticklabels(range(-N, N+1, P // 10))

or directly set your labels by using plt.xticks

abc
  • 11,579
  • 2
  • 26
  • 51
  • Thanks, I think I need to go beyond just using `plt`, as pointed out by Johan C. For those folllowing in my footsteps, you have to change the other bits of code as well. ```ax.set_xticks(ticks) ax.set_xlim(0,P) ax.set_xticklabels(range(-N, N+1, P // 10)) ax.legend()``` – jolene Nov 05 '20 at 17:04