![](/img/trans.png)
[英]How do I add space between the ticklabels and the axes in matplotlib
[英]Matplotlib: Move ticklabels between ticks
我想使用matplotlib創建混淆矩陣的可視化。 下面顯示的方法的參數是類標簽(字母表),分類結果列表(conf_arr)和輸出文件名。 到目前為止,我對結果非常滿意,最后一個問題是:
我無法使網格線之間的軸刻度標簽居中。 如果我將extent參數傳遞給imshow方法,如下所示,網格按照我希望的方式對齊。 如果我把它評論出來,那么網格就會錯位,但標簽是我希望的。 我想我需要一種方法來在關聯的tick和下一個tick之間移動ticklabel,但我不知道是否以及如何做到這一點。
總而言之,我希望左圖像中的網格/刻度,但是像右圖中一樣定位的刻度標記:
def create_confusion_matrix(alphabet, conf_arr, outputname):
norm_conf = []
width = len(conf_arr)
height = len(conf_arr[0])
for i in conf_arr:
a = 0
tmp_arr = []
a = sum(i, 0)
for j in i:
tmp_arr.append(float(j)/float(a))
norm_conf.append(tmp_arr)
fig = plt.figure(figsize=(14,14))
#fig = plt.figure()
plt.clf()
ax = fig.add_subplot(111)
ax.set_aspect(1)
ax.grid(which='major')
res = ax.imshow(np.array(norm_conf), cmap=plt.cm.binary,
interpolation='none', aspect='1', vmax=1,
##Commenting out this line sets labels correctly,
##but the grid is off
extent=[0, width, height, 0]
)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.2)
cb = fig.colorbar(res, cax=cax)
#Axes
ax.set_xticks(range(width))
ax.set_xticklabels(alphabet, rotation='vertical')
ax.xaxis.labelpad = 0.5
ax.set_yticks(range(height))
ax.set_yticklabels(alphabet, rotation='horizontal')
#plt.tight_layout()
plt.savefig(outputname, format='png')
生成的圖像如下所示:
正如您所注意到的,它們默認居中,您通過指定extent=[0, width, height, 0]
來覆蓋默認行為。
有很多方法可以解決這個問題。 一種是使用pcolor
並將edgecolors和linestyles設置為看起來像網格線(你實際上需要pcolor
而不是pcolormesh
才能工作)。 但是,您必須更改范圍以獲得中心的刻度,默認情況下為imshow
。
import matplotlib.pyplot as plt
import numpy as np
data = np.random.random((10,10))
labels = 'abcdefghij'
fig, ax = plt.subplots()
im = ax.pcolor(data, cmap='gray', edgecolor='black', linestyle=':', lw=1)
fig.colorbar(im)
# Shift ticks to be at 0.5, 1.5, etc
for axis in [ax.xaxis, ax.yaxis]:
axis.set(ticks=np.arange(0.5, len(labels)), ticklabels=labels)
plt.show()
或者,您可以打開次要網格並將其放在像素邊界處。 因為你想要固定標簽,我們只需手動設置所有內容。 否則, MultipleLocator
會更有意義:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.random((10,10))
labels = 'abcdefghij'
fig, ax = plt.subplots()
im = ax.imshow(data, cmap='gray', interpolation='none')
fig.colorbar(im)
# Set the major ticks at the centers and minor tick at the edges
locs = np.arange(len(labels))
for axis in [ax.xaxis, ax.yaxis]:
axis.set_ticks(locs + 0.5, minor=True)
axis.set(ticks=locs, ticklabels=labels)
# Turn on the grid for the minor ticks
ax.grid(True, which='minor')
plt.show()
或者:你試過im = ax.matshow(data, cmap='gray')
而不是imshow()
嗎? 這也應該將ticklabels放在正確的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.