0

I want to plot a numpy array but I want to change the x ticks value of the plot. I want to have negative index, from instance for an array of size 20, I want to have x ticks in range of [-9,10]

I tried this code:

import numpy as np
import matplotlib.pyplot as plt

size = 20

seq = np.full(size, 1)
for i in range(size//2, size):
    seq[i] = 0

fig, ax = plt.subplots()
ax.plot(seq)
ax.set_xlabel('x')
ax.set_xticks(np.arange(-size//2+1, size//2+1, 1))
plt.show()

But I have an unexpected result:

enter image description here

2 Answers 2

1

You can use plt.xticks() instead of ax.set_xticks()

import numpy as np
import matplotlib.pyplot as plt

size = 20

seq = np.full(size, 1)
for i in range(size//2, size):
    seq[i] = 0

fig, ax = plt.subplots()
ax.plot(seq)
ax.set_xlabel('x')
plt.xticks(labels=np.arange(-size//2+1, size//2+1, 1),
           ticks=range(size),
           rotation=0)
plt.show()

result

Sign up to request clarification or add additional context in comments.

1 Comment

I prefer used ax.set_xticks() but with your solution I see that I can use ax.set_xticklabels, so with ax.set_xticks(range(size)) and ax.set_xticklabels(np.arange(-size//2+1, size//2+1, 1)), it's work as excepted, thank you for your help !
0

I resolved the problem using ax.plot(np.arange(-size//2+1, size//2+1, 1), seq) that plot the numpy array with the x ticks I wanted, the result:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.