Home > front end >  x-axis ticks change location when data is None - matplotlib
x-axis ticks change location when data is None - matplotlib

Time:02-20

I plotted a list using:

fig = plt.figure(1)
ax1 = fig.add_subplot(111)
ax1.plot(range(samples_per_ant[0]), new_y[:samples_per_ant[0]], '-o', linewidth=3)

The result is that the ticks are in the right positions, equally spaced in between and from the plot's frame (i can't add a picture to share).

But when i want to change the ticks i used:

ax1.set_xticks(range(samples_per_ant[0]), case[:samples_per_ant[0]])

since the last few elements in list "new_y" are "None", such as

new_y = [1, 2, 3, ... , None, None, None]

it looks like it "stretched" the x-axis a bit and the ticks got to the right edge of the frame (no space from the edge, as supposed to be).

How can i plot it and keep the ticks in place?

CodePudding user response:

As you manually set your x-tick labels, you should also take care manually of the x-axis limits:

from matplotlib import pyplot as plt

new_y = [1, 5, 3, 7 , None, 8, None, -1]
case = list("ABCDEFGHIJKL")
n = 7

fig = plt.figure(1)
ax1 = fig.add_subplot(111)
ax1.plot(range(n), new_y[:n], '-o', linewidth=3)
ax1.set_xticks(range(n), case[:n])
ax1.set_xlim(-0.3, n-0.7)

plt.show()

Sample output: enter image description here

  • Related