How to change xticks with matplotlib?

Viewed 18921

I want to change xticks on a plot with matplotlib, say replacing for instance with a string. According to matplotlib manual https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.xticks.html I did the following code :

import matplotlib.pyplot as plt
import numpy as np

x=np.arange(10)
y=x**2
plt.figure()
plt.plot(x,y)
locs, labels=plt.xticks()
new_xticks=['test' for d in locs]
plt.xticks(new_xticks, rotation=45, horizontalalignment='right')

The problem is when I do this, ticks on x axis are not modified, and I get the following error

ConversionError: Failed to convert value(s) to axis units: ['test', 'test', 'test', 'test', 'test', 'test', 'test']

EDIT : I want to have the ticks at the same place of the original plot, which x axis don't go beyond min and max value, as in the following picture : plot

Thanks in advance for your help !

EDIT2 : its not a duplicate as I do it directly without using subplots

2 Answers

Do something like this:

import matplotlib.pyplot as plt
import numpy as np

x=np.arange(10)
y=x**2
plt.figure()
plt.plot(x,y)
locs, labels=plt.xticks()
x_ticks = []
new_xticks=['test' for d in locs]
plt.xticks(locs,new_xticks, rotation=45, horizontalalignment='right')
plt.show()

Output:

enter image description here

You are modifying the ticks. But the ticks need to be numbers. If you want to modify the tick-labels you can do so via

plt.xticks(locs, new_xticks)
Related