在matplotlib中将轴标签添加到带有hinton图的子图中,而不破坏i

2024-09-30 03:23:11 发布

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

我发现了这个关于如何用matplotlib:http://www.scipy.org/Cookbook/Matplotlib/HintonDiagrams制作hinton图的示例。在

我需要多个图表和一个在记号上有标签的yaxis,所以我像这样重写它

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(),则无法获取任何ytick标签
  2. 如果保持轴打开,我会在底部子图周围得到大的空白矩形
  3. 即使把轴放在一边,上面的子图和下面的子图之间有一个很大的间隙,我无法缩小

那么,我怎样才能得到ytick标签,但没有大的白色长方形围绕子ig和没有大的差距之间的顶部和底部?在


Tags: rmdefrandom标签widtharrayw1hs
1条回答
网友
1楼 · 发布于 2024-09-30 03:23:11

你的代码仍然不完整。但是,如果您只想调整子批次之间的间距,有选择地删除一些级别,您可以尝试:

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

相关问题 更多 >

    热门问题