[英]2 confusion matrix, 1 colorbar
我想產生兩個混淆矩陣,只顯示一個色標。 我基本上是試圖將此scikit-learn代碼與此答案合並。
我的代碼如下所示:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=1, ncols=2)
classes = ["A", "B"]
for i, ax in enumerate(axes.flat):
cm = np.random.random((2,2))
im = ax.imshow(cm, vmin=0, vmax=1)
plt.title("Title {}".format(i))
tick_marks = np.arange(2)
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], '.5f'),
horizontalalignment="center",
color="white")
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.tight_layout()
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.88, 0.15, 0.05, 0.6])
fig.colorbar(im, cax=cbar_ax)
plt.show()
因此,所有內容都繪制在最后一張圖像上。 兩個問題:
您將所有元素繪制在最后一張圖像上,因為您將pyplot
( plt.xxxxx()
)接口與面向對象的接口混合在一起。 請參考這個問題,或者這個對於一些解釋。
對於顏色條,有很多方法可以獲取適當大小的顏色條 (例如,使用@DavidG建議的GridSpec和AxisDivider進行播放)。 因為您有兩個使用imshow
軸,所以根據類似問題的答案 ,我建議您改用ImageGrid
。
您的代碼應為:
import itertools
from mpl_toolkits.axes_grid1 import ImageGrid
classes = ["A", "B"]
fig = plt.figure()
grid = ImageGrid(fig, 111, # as in plt.subplot(111)
nrows_ncols=(1,2),
axes_pad=0.15,
cbar_location="right",
cbar_mode="single",
cbar_size="7%",
cbar_pad=0.15,
)
for i, ax in enumerate(grid[:2]):
cm = np.random.random((2,2))
im = ax.imshow(cm, vmin=0, vmax=1)
ax.set_title("Title {}".format(i)) # ax.___ instead of plt.___
tick_marks = np.arange(2)
ax.set_xticks(tick_marks) # Warning: different signature for [x|y]ticks in pyplot and OO interface
ax.set_xticklabels(classes, rotation=45)
ax.set_yticks(tick_marks)
ax.set_yticklabels(classes)
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
ax.text(j, i, format(cm[i, j], '.5f'),
horizontalalignment="center",
color="white")
ax.set_ylabel('True label')
ax.set_xlabel('Predicted label')
fig.tight_layout()
fig.subplots_adjust(right=0.8)
fig.colorbar(im, cax=ax.cax)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.