在 gridspec 单元格内调整 matplotlib 对象的大小(matshow 和 colorbar 大小不匹配)
Resize matplotlib object within gridspec cell (matshow and colorbar size mismatched)
matshow 和 colorbar 对象在 gridspec 单元格内填充的内容不同 space,因此它们的高度不同。
通常我会使用 colorbar 'shrink' 参数,但是当嵌套在 gridspec 对象中时这似乎不起作用
如何在不调整 matshow 热图大小的情况下缩小颜色条对象?
提前致谢
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()
编辑:带注释的图像以供澄清
您可以使用 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()
这会产生下图,在我看来它们大小相同:
matshow 和 colorbar 对象在 gridspec 单元格内填充的内容不同 space,因此它们的高度不同。
通常我会使用 colorbar 'shrink' 参数,但是当嵌套在 gridspec 对象中时这似乎不起作用
如何在不调整 matshow 热图大小的情况下缩小颜色条对象?
提前致谢
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()
编辑:带注释的图像以供澄清
您可以使用 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()
这会产生下图,在我看来它们大小相同: