0

Here is a sample code:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
y = np.sin(x)
ax.plot(x, y, marker='s')
ax.set_xlabel('angle')
ax.set_title('sine')
#ax.set_xticklabels([" ",1,2,3,4,5," "]) # don't work
ax.set_yticks([-1,0,1])
plt.show()

It creates this Figure:

Figure 1

For the x-axis, I would like to amend the x-axis ticklabels to only show 1,2,3,4,5 while I would like to blank-out 0 and 6. I tried ax.set_xticklabels([" ",1,2,3,4,5," "]) but this did not work. I get this outcome instead:

wrong

and this warning msg:

Warning (from warnings module):
  File "~/test.py", line 12
    ax.set_xticklabels(["",1,2,3,4,5,""]) # don't work
UserWarning: FixedFormatter should only be used together with FixedLocator

How do I amend the x-axis ticklabels to only show 1,2,3,4,5?

Sun Bear
  • 7,594
  • 11
  • 56
  • 102

1 Answers1

1

You could just set the xticks with ax.set_xticks before calling your ax.set_xticklabels function. See code below:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
y = np.sin(x)
ax.plot(x, y, marker='s')
ax.set_xlabel('angle')
ax.set_title('sine')
ax.set_xticks(np.arange(7))
ax.set_xticklabels([" ",1,2,3,4,5," "]) 
ax.set_yticks([-1,0,1])
plt.show()

And the output gives:

enter image description here

jylls
  • 4,395
  • 2
  • 10
  • 21
  • 1
    Thanks. For ver 3.5, I discovered that `ax.set_xticks(np.arange(7), labels=["",'1','2','3','4','5',""])` works too. A single line command instead of using two lines of command. – Sun Bear Dec 04 '21 at 20:58