python-3.x - 绘制矩阵时在辅助颜色栏中显示行总和
问题描述
我正在使用matshow
. 我有一个数组
sum = np.sum(A, axis=0)
我想将存储的值显示sum
为辅助图例。
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
A = np.arange(0,100).reshape(10,10)
plt.matshow(A)
plt.colorbar()
我想知道如何在上面的代码中添加辅助图例。
例如预期输出:
右侧的图例是自动创建的。通过次要图例,我的意思是底部显示的色标。例如,这可能对应于每列中值的总和(y 轴条目)。
解决方案
我认为您需要重新考虑为什么需要在颜色条上表示列总和。因为颜色条上的颜色代表矩阵中的一个值。列总和的值甚至不包括在内,用彩条显示列总和是什么意思?
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
fig, ax = plt.subplots(figsize=(4,4))
A = np.arange(0,100).reshape(10,10)
column_sum = A.sum(axis=0)
im2 = ax.matshow(np.expand_dims(column_sum, axis=0))
# Override upper matrix
im = ax.matshow(A)
fig.colorbar(im2, orientation="horizontal") # Note: the color in this color bar represents value in im2, im2 is override by im. To distinguish it from im, you may interested in https://matplotlib.org/gallery/images_contours_and_fields/custom_cmap.html
fig.colorbar(im)