[英]How to amend matplotlib x-axis ticklabels?
這是一個示例代碼:
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()
它創建了這個圖:
對於 x 軸,我想將 x 軸刻度標簽修改為僅顯示 1、2、3、4、5,而我想清除 0 和 6。我嘗試ax.set_xticklabels([" ",1,2,3,4,5," "])
但這不起作用。 我得到了這個結果:
這個警告信息:
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
如何修改 x 軸刻度標簽以僅顯示 1、2、3、4、5?
您可以在調用ax.set_xticklabels
ax.set_xticks
之前使用 ax.set_xticks 設置 xticks。 請參見下面的代碼:
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()
output 給出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.