Matplotlib颜色条没有缩小

时间:2019-09-27 11:09:16

标签: python python-3.x matplotlib

我在下面的代码中使用自定义颜色条

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

cmap = matplotlib.cm.get_cmap("hot")
norm = matplotlib.colors.Normalize(vmin=0, vmax=10)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
fig = plt.figure()
gs = GridSpec(10, 10, figure=fig)
ax = fig.add_subplot(gs[1:, :])
colorbar_ax = fig.add_subplot(gs[0, :])
plt.colorbar(cax=colorbar_ax, mappable=sm, orientation="horizontal",
                 shrink=0.5)
plt.tight_layout()
plt.show()

这给了我以下输出, enter image description here

对于其他代码的其他方面,我不得不使用gridspec。如何将颜色条缩小一半(或其他分数)? shrink=0.5fraction=0.5无法正常工作。

1 个答案:

答案 0 :(得分:1)

来自documentation for colorbar

  

收缩变形提供了一种简单的方法来缩放颜色条   相对于轴。请注意,如果指定了cax,它将确定   忽略颜色条的大小,缩小和纵横比。

因此,如果您使用的是gridspec,则不能使用shrink

当然,gridspec旨在简化子图轴的大小设置,因此我们可以使用它来定义颜色条轴的大小。由于您已经有由gridspec定义的10x10网格,因此我们可以只使用x方向上的中间部分。例如,您可以将其更改为以下内容以缩短颜色栏:

colorbar_ax = fig.add_subplot(gs[0, 3:7])