Creating xticks in Python plot based on a range

256 Views Asked by At

I'm trying to change the xticks in a Python graph from a long list of 280 values (all numbers) to only show every 20 or so. Here is the code I've been playing with:

p = 20
ax.xaxis.set_ticks(range(0,len(x), p), [x[i] for i in range(len(x)) if i % p == 0])

I have also tried to use the function ax.set_xticks as well, but neither gives me what I was hoping for which is tick marks only for the values 0, 20, 40, 60, etc.

Thanks,

1

There are 1 best solutions below

0
On

I think you can just insert an empty label in place!

Maybe try something like this:

import matplotlib.pyplot as plt
import numpy as np

x=np.arange(10)
y=2*x
plt.figure()
plt.plot(x,y)
locs, labels=plt.xticks()
x_ticks = []

step=3
new_xticks=[]
for x in locs:
  if (x % step == 0):
    new_xticks.append(x)
  else:
   new_xticks.append(None)

plt.xticks(locs,new_xticks, rotation=45, horizontalalignment='right')
plt.show()

Which should give something like this

enter image description here