4

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

JohnBranson
  • 91
  • 1
  • 1
  • 6

2 Answers2

2

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

arajshree
  • 626
  • 4
  • 13
  • 1
    Thanks a lot but I still have a problem : In this case the first value is before the beginning of the plot and the last is after. How to replace by the string the same values and scale as the plot without this ? – JohnBranson Jun 25 '19 at 10:08
1

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)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712