Home > Enterprise >  Remove the x-axis spikes with empty labels in matplotlib
Remove the x-axis spikes with empty labels in matplotlib

Time:12-11

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!

CodePudding user response:

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

  • Related