0

I have a plot in which I have to divide my data points into several groups, so I made customized sticks for this plot.

For instance, I have to group data points into multiples of 12, this is what I did

my_xticks = []
for x_ele in range(len(all_points)):
    if x_ele % 12 == 0:
        my_xticks.append(x_ele//12 + 1)
    else:
        my_xticks.append('')

ax.set_xticks(range(len(my_xticks)))
ax.set_xticklabels(my_xticks)

And the x-axis of the plot looks as enter image description here

However, I wish to remove those spikes with empty labels, as circled in red enter image description here

So the final x-axis could look like enter image description here

Any idea? Thanks!

Hang Chen
  • 549
  • 1
  • 7
  • 18

1 Answers1

1

You didn't provide any data so i solved this by using some data i created. the idea is to use the range function to create the same gap between each tick.

Here is my code:

from matplotlib import pyplot as plt
import numpy as np

# create sample data
x = np.linspace(1, 60, 100)
y = x*x

# define the space of ticks
space = 12
# get minimum x value
min_val = int(min(x))
# get maximum x value
max_val = int(max(x))
# define our ticks
xticks = list(range(min_val, max_val, space))
# define labels for each tick
xticklabels = list(range(1, len(xticks) + 1, 1))

# create plot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xticks(xticks)
ax.set_xticklabels(xticklabels)
plt.show()

And output:

Output

RoseGod
  • 1,206
  • 1
  • 9
  • 19
  • 1
    Thank you so much this works! I should have provided the entire code with data. I found that I did not actually have a good understanding of the logic behind `ax.set_xticks()` so I did not use it properly. Thank you again! – Hang Chen Dec 10 '21 at 19:14