X轴在matplotlib中是固定大小的(无法用set_xlim更改)

时间:2015-03-25 15:28:31

标签: python matplotlib

我想删除我正在绘制的Hinton图中x轴的部分白色部分(见下文)。我尝试使用ax1.set_xlim(1.5, width-4),但这只是将空白区域移动到数据的左侧。用灰色填充白色空间会很容易,但我对此并不感兴趣。

即使我使用ax1.set_ylim(0, height)更改y轴,x轴也会改变..

enter image description here

def _blob(x,y,area,colour):
    """
    Draws a square-shaped blob with the given area (< 1) at
    the given coordinates.
    """
    hs = np.sqrt(area) / 2
    xcorners = np.array([x - hs, x + hs, x + hs, x - hs])
    ycorners = np.array([y - hs, y - hs, y + hs, y + hs])
    P.fill(xcorners, ycorners, colour, edgecolor=colour)

def hinton(W, varLabels, maxWeight=None):
    """
    Draws a Hinton diagram for visualizing a weight matrix. 
    Temporarily disables matplotlib interactive mode if it is on, 
    otherwise this takes forever.
    """
    reenable = False
    if P.isinteractive():
        P.ioff()
    P.clf()
    height, width = W.shape
    if not maxWeight:
        maxWeight = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2))

    fig  = plt.figure()  
    ax1  = fig.add_subplot(111) 
    ax1.set_xticks(np.arange(0,12))
    ax1.set_yticks(np.arange(0,12))
    ax1.tick_params(direction='inout')
    ax1.set_xticklabels(varLabels, rotation=45, ha='right')  
    ax1.set_yticklabels(["" for x in range(12)])    

    P.fill(np.array([0-0.5,width-0.5,width-0.5,0-0.5]),np.array([0-0.5,0-0.5,height,height]),'gray')
    #P.axis('off')
    P.axis('equal')
    for x in xrange(width):
        for y in xrange(height):
            _x = x+1
            _y = y+1
            w = W[y,x]
            if w > 0:
                _blob(_x - 1, height - _y + 0.5, min(1,w/maxWeight),'white')
            elif w < 0:
                _blob(_x - 1, height - _y + 0.5, min(1,-w/maxWeight),'black')
    ax1.set_xlim(1.5, width-1)
    if reenable:
        P.ion()
    P.show()


# Run the plot function
varLabels = ['n_contacts', 'n_calls', 'n_texts', 'dur_calls', 'morning', 'work-hours', 'evening', 'night', 'weekdays', 'friday', 'saturday', 'sunday']
hinton(conv_weights, varLabels)

1 个答案:

答案 0 :(得分:1)

ax1.set_xlim(-0.5, width-0.5)
ax1.set_aspect('equal','box')

而不是

ax1.set_xlim(1.5, width-1)