matshow和colorbar对象不会填充gridspec单元格内的相同空间,因此它们的高度不同。
通常我会使用colorbar'shrow'参数,但是当嵌套在gridspec对象中时这似乎不起作用
如何在不调整matshow热图的情况下缩小colorbar对象?
提前致谢
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import gridspec
df = pd.DataFrame((np.random.randint(0, 3, 10000).reshape(100, 100)))
fig = plt.figure(figsize=(15,15))
gs = gridspec.GridSpec(10, 10)
#### other axes removed for simplicity
ax2 = fig.add_subplot(gs[2:,:8])
# plot heatmap
cax = ax2.matshow(df, interpolation='nearest', cmap=plt.cm.YlGn, aspect='equal')
ax2.set_xticks([])
ax2.set_yticks([])
ax3 = fig.add_subplot(gs[2:,8])
fig.colorbar(cax, cax=ax3)
plt.tight_layout()
gs.update(wspace=2, hspace=0.1)
plt.show()
答案 0 :(得分:2)
您可以使用matplotlib AxesDivider。以下是使用您问题中的数据的示例:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import gridspec
fig = plt.figure(figsize=(15,15))
df = pd.DataFrame((np.random.randint(0, 3, 10000).reshape(100, 100)))
gs = gridspec.GridSpec(10, 10)
ax2 = fig.add_subplot(gs[2:,:8])
im = ax2.matshow(df,interpolation='nearest',cmap=plt.cm.YlGn, aspect='equal')
divider = make_axes_locatable(ax2)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
plt.show()
这会产生下面的图表,我觉得它们的大小相同: