在matplotlib中为hinton图的子图添加轴标签而不破坏它

0 投票
1 回答
962 浏览
提问于 2025-04-17 07:38

我在网上找到一个关于如何用matplotlib画Hinton图的例子:http://www.scipy.org/Cookbook/Matplotlib/HintonDiagrams

因为我需要画多个图,并且想在y轴上加上刻度标签,所以我把代码改成了这样:

import matplotlib.pyplot as plt
import numpy as N

def hintonForTwo(W1, W2, maxWeight=None):

    height, width = W1.shape
    if not maxWeight:
        maxWeight = 2**N.ceil(N.log(N.max(N.abs(W1)))/N.log(2))

    fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, sharey=True)

    hintonSubPlot(ax1, W1, maxWeight)
    ax1.set_yticks(N.arange(height))
    # the input matrices will have row height of 7
    # and years 1981, 1986... up to 2011 are supposed to be the ytick labels
    ax1.set_yticklabels(tuple(range(1981,2012,5)))
    ax1.set_aspect('equal')
    ax1.set_axis_off()
    hintonSubPlot(ax2, W2, maxWeight)
    return fig, ax1, ax2

def hintonSubPlot(F, W, maxWeight):
    height, width = W.shape
    F.fill(N.array([0,width,width,0]),N.array([0,0,height,height]),'white')

    for x in xrange(width):
        for y in xrange(height):
                _x = x+1
            _y = y+1
            w = W[y,x]
            if w > 0:
                _blobAlt(F, _x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'black')
            elif w < 0:
                _blobAlt(F, _x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'gray')
    return F

def _blobAlt(F, x,y,area,colour):
    hs = N.sqrt(area) / 2
    xcorners = N.array([x - hs, x + hs, x + hs, x - hs])
    ycorners = N.array([y - hs, y - hs, y + hs, y + hs])
    F.fill(xcorners, ycorners, colour, edgecolor=colour)

dim = (7,50)
X1 = N.ones(dim) * N.nan
X2 = N.ones(dim) * N.nan

rm = N.random.random(dim)
X1[rm > 2.0/3] = 1
X1[rm < 1.0/3] = -1

rm = N.random.random(dim)
X2[rm > 2.0/3] = 1
X2[rm < 1.0/3] = -1

f, a, b = hintonForTwo(X1, X2)
f.savefig('tmp.png')

不过我遇到了一些问题,自己解决不了:

  1. 如果我用ax1.set_axis_off(),就看不到任何y轴的刻度标签了。
  2. 如果不把坐标轴关掉,底部的子图周围会出现大块空白的矩形。
  3. 即使把坐标轴关掉,顶部和底部的子图之间还是有很大的空隙,我也没法缩小。

那么我该怎么才能在不出现大白色矩形的情况下显示y轴刻度标签,并且消除顶部和底部之间的空隙呢?

1 个回答

0

你的代码还没有写完。不过,如果你只是想调整子图之间的间距,或者选择性地去掉一些层级,你可以试试下面的代码:

import numpy as np
import pylab as p


fig = p.figure()
fig.subplots_adjust(left=0.145, bottom=0.13, right=.87, top=.975, wspace=.18, hspace=.10)

x=np.arange(1,10,0.01)
ax1=fig.add_subplot(211)
ax1.plot(x,np.sin(x),'ro')
ax1.set_ylabel('sin(x)')

ax2=fig.add_subplot(212,sharex=ax1,sharey=ax1)
ax2.plot(x,np.cos(x),'bs')
ax2.set_xlabel('x')
ax2.set_ylabel('cos(x)')

for label in ax1.get_xticklabels():
    label.set_visible(False)

p.show()

Plot

撰写回答