Home > Net >  Matplotlib having different x ticks that the index from numpy array
Matplotlib having different x ticks that the index from numpy array

Time:07-29

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

CodePudding user response:

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()

enter image description here

  • Related