get_position()在使用colorb时会执行奇怪的操作

2024-04-26 13:55:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据矩阵,其中x轴和y轴是对数的。我试图使用imshow来显示矩阵,但是由于我想要记录轴,所以我将imshow轴中的记号设置为[],然后覆盖另一组轴:

import matplotlib.pyplot as plt
import numpy as np

# the x,y max and min are the log values
array = np.zeros((2,2))
array[1,1] = -1
fig = plt.figure()
ax = plt.imshow(
    array, 
    extent = (0,1, 1, 0), 
    interpolation = 'nearest').get_axes()
ax.invert_yaxis()

# add a colorbar
# cb = plt.colorbar()      # <----- THIS CAUSES TROUBLE
# cb.set_label('zbar')

ax.set_aspect(1)
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
position = ax.get_position()
aspect = ax.get_aspect()

# overlay another set of axes 
ax_log = fig.add_subplot(111, frameon = False)
ax_log.set_xscale('log')
ax_log.set_yscale('log')
ax_log.axis((10**0, 10**1, 10**0, 10**1)) # old min and max but exponentiated  
ax_log.set_position(position)
ax_log.set_aspect(aspect)

plt.savefig('test.png', bbox_inches = 'tight')
plt.close()

没有colorbar,效果很好:

with no colorbar

但是当我取消了添加colorbar的行的注释时,我得到了一个奇怪的转变:

with colorbar

看起来colorbar以某种方式将图像稍微向左移动,但是考虑到我在创建colorbar之后调用get_position(),这看起来很奇怪。我是不是忽略了一个更容易制作这个情节的方法?有什么简单的办法吗?在


Tags: theimportloggetasnppositionplt
1条回答
网友
1楼 · 发布于 2024-04-26 13:55:56

找了一下,我找到了一个解决办法,也许还有更好的。。。在

问题似乎是plt.colorbar()会从它绘制的图中“窃取”空间。这仍然有点奇怪,因为我仍然希望get_position()返回正确的坐标。但是作为一种解决方法,我使用了GridSpec和原始的Colorbar构造函数。在

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
from matplotlib.colorbar import Colorbar

# the x,y max and min are the log values
array = np.zeros((2,2))
array[1,1] = -1
fig = plt.figure()
gs = GridSpec(10,11)            # create a 10 x 11 grid
ax = plt.subplot(gs[:,0:-1])    # make subplot on 10 x 10 part 
im = plt.imshow(
    array, 
    extent = (0,1, 1, 0), 
    interpolation = 'nearest', 
    axes = ax)
ax.invert_yaxis()

# add a colorbar
cb_ax = plt.subplot(gs[:,-1])   # put the colorbar on the last column
cb = Colorbar(ax = cb_ax, mappable = im ) # use the raw colorbar constructor
cb.set_label('zbar')

ax.set_aspect(1)
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
position = ax.get_position()
aspect = ax.get_aspect()

# overlay another set of axes 
ax_log = fig.add_subplot(111, frameon = False) # can't use gridspec?
ax_log.set_xscale('log')
ax_log.set_yscale('log')
ax_log.axis((10**0, 10**1, 10**0, 10**1)) # old min and max but exponentiated  
ax_log.set_position(position)
ax_log.set_aspect(aspect)

plt.savefig('test.pdf', bbox_inches = 'tight')
plt.close()

同样奇怪的是,我不能使用GridSpec对象初始化第二组轴(这样做会使图像消失)。在

相关问题 更多 >