简体   繁体   中英

How to amend matplotlib x-axis ticklabels?

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:

图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:

错误的

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?

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM