Skip to content

Commit 1b29e57

Browse files
committed
added matshow
svn path=/trunk/matplotlib/; revision=912
1 parent 770d0a0 commit 1b29e57

File tree

5 files changed

+129
-13
lines changed

5 files changed

+129
-13
lines changed

CHANGELOG

+2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
New entries should be added at the top
22

3+
2005-02-02 Incorporated Fernando's matshow
4+
35
2005-02-01 Added Fernando's figure num patch, including experemental
46
support for pylab backend switching, LineCOllection.color
57
warns, savefig now a figure method, fixed a close(fig) bug

TODO

+5-1
Original file line numberDiff line numberDiff line change
@@ -642,4 +642,8 @@ ZeroDivisionError: SeparableTransformation::eval_scalars yin interval is zero; c
642642

643643
-- fix contour mappable to work under changes in clim, cmap
644644

645-
-- port colorbar, current mappable to API
645+
-- port colorbar, current mappable to API
646+
647+
-- add qt / gpl warning
648+
649+
-- Nil's xtick labeling bug

lib/matplotlib/figure.py

+43-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from text import Text, _process_text_args
1111
from legend import Legend
1212
from transforms import Bbox, Value, Point, get_bbox_transform, unit_bbox
13-
13+
from numerix import array, clip
1414

1515

1616
class Figure(Artist):
@@ -454,3 +454,45 @@ def savefig(self, *args, **kwargs):
454454

455455
self.canvas.print_figure(*args, **kwargs)
456456

457+
458+
def figaspect(arr):
459+
"""
460+
Determine the width and height for a figure that would fit array
461+
preserving aspcect ratio. The figure width, height in inches are
462+
returned. Be sure to create an axes with equal with and height, eg
463+
464+
w, h = figaspect(A)
465+
fig = Figure(figsize=(w,h))
466+
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
467+
ax.imshow(A, **kwargs)
468+
469+
Thanks to Fernando Perez for this function
470+
"""
471+
472+
# min/max sizes to respect when autoscaling. If John likes the idea, they
473+
# could become rc parameters, for now they're hardwired.
474+
figsize_min = array((4.0,2.0)) # min length for width/height
475+
figsize_max = array((16.0,16.0)) # max length for width/height
476+
#figsize_min = rcParams['figure.figsize_min']
477+
#figsize_max = rcParams['figure.figsize_max']
478+
479+
# Extract the aspect ratio of the array
480+
nr,nc = arr.shape[:2]
481+
arr_ratio = float(nr)/nc
482+
483+
# Height of user figure defaults
484+
fig_height = rcParams['figure.figsize'][1]
485+
486+
# New size for the figure, keeping the aspect ratio of the caller
487+
newsize = array((fig_height/arr_ratio,fig_height))
488+
489+
# Sanity checks, don't drop either dimension below figsize_min
490+
newsize /= min(1.0,*(newsize/figsize_min))
491+
492+
# Avoid humongous windows as well
493+
newsize /= max(1.0,*(newsize/figsize_max))
494+
495+
# Finally, if we have a really funky aspect ratio, break it but respect
496+
# the min/max dimensions (we don't want figures 10 feet tall!)
497+
newsize = clip(newsize,figsize_min,figsize_max)
498+
return newsize

lib/matplotlib/pylab.py

+77-9
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
ishold - return the hold state of the current axes
4747
legend - make an axes legend
4848
loglog - a log log plot
49+
matshow - display a matrix in a new figure preserving aspect
4950
pcolor - make a pseudocolor plot
5051
pie - make a pie chart
5152
plot - make a line plot
@@ -195,7 +196,7 @@
195196
from cbook import flatten, is_string_like, exception_to_str, popd, silent_list, iterable
196197
from colors import normalize
197198
from cm import ColormapJet, Grayscale, get_cmap
198-
from figure import Figure
199+
from figure import Figure, figaspect
199200
import image
200201
from matplotlib import rcParams, rcParamsDefault, get_backend
201202
from backend_bases import FigureCanvasBase
@@ -336,6 +337,7 @@ def plotting():
336337
loglog - a log log plot
337338
imread - load image file into array
338339
imshow - plot image data
340+
matshow - display a matrix in a new figure preserving aspect
339341
pcolor - make a pseudocolor plot
340342
plot - make a line plot
341343
psd - make a plot of power spectral density
@@ -1598,6 +1600,71 @@ def switch_backend(newbackend):
15981600
from backends import new_figure_manager, error_msg, \
15991601
draw_if_interactive, show
16001602

1603+
1604+
def matshow(*args,**kw):
1605+
"""Display an array as a matrix.
1606+
1607+
The origin is set at the upper left hand corner and rows (first dimension
1608+
of the array) are displayed horizontally. The aspect ratio of the figure
1609+
window is that of the array, as long as it is possible to fit it within
1610+
the constraints of your figure.figsize_min/max parameters with no
1611+
stretching. If the window dimensions can't accomodate this (extremely
1612+
tall/wide arrays), some stretching will inevitably occur.
1613+
1614+
matshow() calls imshow() with Aargs and **kwargs, but by default
1615+
it sets interpolation='nearest' (unless you override it). All
1616+
other arguments and keywords are passed to imshow(), so see its
1617+
docstring for further details.
1618+
1619+
Tick labels for the xaxis are placed on top by default.
1620+
1621+
return value is a (fig, ax, im) tuple
1622+
1623+
Example usage:
1624+
1625+
def samplemat(dims):
1626+
aa = zeros(dims)
1627+
for i in range(min(dims)):
1628+
aa[i,i] = i
1629+
return aa
1630+
1631+
dimlist = [(12,12),(128,64),(64,512),(2048,256)]
1632+
1633+
1634+
for i, d in enumerate(dimlist):
1635+
fig, ax, im = matshow(samplemat(d))
1636+
show()
1637+
1638+
"""
1639+
1640+
arr = args[0]
1641+
w,h = figaspect(arr)
1642+
fig = figure(figsize=(w,h))
1643+
ax = fig.add_axes([0.0, 0.05, 0.8, 0.8])
1644+
1645+
ax.xaxis.tick_top()
1646+
ax.title.set_y(1.05) # raise it up a bit for tick top
1647+
# Call with 'lower' origin (we'll flip axes later)
1648+
kw['origin'] = 'lower'
1649+
1650+
# We also set a 'free' aspect ratio b/c we've already done our best to fix
1651+
# it, while preserving the dimension sanity checks. At this point, if a
1652+
# bit of rescaling is needed, so be it. Otherwise, we'd get the nasty
1653+
# white bands we're working so hard to prevent.
1654+
kw['aspect'] = 'free'
1655+
1656+
# Unless overridden, don't interpolate
1657+
kw.setdefault('interpolation','nearest')
1658+
1659+
# All other keywords go through to imshow.
1660+
im = ax.imshow(*args,**kw)
1661+
1662+
# set the x and y lim to equal the matrix dims
1663+
nr,nc = arr.shape[:2]
1664+
ax.set_xlim((0,nc))
1665+
ax.set_ylim((nr,0))
1666+
return fig, ax, im
1667+
16011668

16021669
### The following functions were autogenerated by the boilerplate.py
16031670
### script. They are simple wrappers around the Axes methods of the
@@ -2520,22 +2587,23 @@ def winter():
25202587

25212588
__plotting_all__ = [
25222589
# plotting
2590+
25232591
'plotting', 'colormaps', 'get_current_fig_manager', 'connect',
25242592
'disconnect', 'get_plot_commands', 'raise_msg_to_str', 'axis',
25252593
'axes', 'delaxes', 'clim', 'close', 'clf', 'colorbar', 'draw',
25262594
'figtext', 'figimage', 'figlegend', 'figure', 'gca', 'gcf', 'gci',
25272595
'get', 'hold', 'ishold', 'isinteractive', 'imread', 'load', 'rc',
2528-
'rcdefaults', 'save', 'savefig', 'set', 'subplot', 'twinx', 'title',
2529-
'xlabel', 'ylabel', 'xlim', 'ylim', 'xticks', 'rgrids',
2596+
'rcdefaults', 'save', 'savefig', 'set', 'subplot', 'twinx',
2597+
'title', 'xlabel', 'ylabel', 'xlim', 'ylim', 'xticks', 'rgrids',
25302598
'thetagrids', 'yticks', 'polar', 'over', 'ioff', 'ion', 'axhline',
25312599
'axhspan', 'axvline', 'axvspan', 'bar', 'barh', 'cohere',
25322600
'contour', 'csd', 'errorbar', 'fill', 'hist', 'hlines', 'imshow',
2533-
'loglog', 'pcolor', 'pcolor_classic', 'pie', 'plot', 'plot_date',
2534-
'psd', 'scatter', 'scatter_classic', 'semilogx', 'semilogy',
2535-
'specgram', 'spy', 'spy2', 'stem', 'vlines', 'cla', 'grid',
2536-
'legend', 'table', 'text', 'autumn', 'bone', 'cool', 'copper',
2537-
'flag', 'gray', 'hot', 'hsv', 'jet', 'pink', 'prism', 'spring',
2538-
'summer', 'winter',
2601+
'loglog', 'matshow', 'pcolor', 'pcolor_classic', 'pie', 'plot',
2602+
'plot_date', 'psd', 'scatter', 'scatter_classic', 'semilogx',
2603+
'semilogy', 'specgram', 'spy', 'spy2', 'stem', 'vlines', 'cla',
2604+
'grid', 'legend', 'table', 'text', 'autumn', 'bone', 'cool',
2605+
'copper', 'flag', 'gray', 'hot', 'hsv', 'jet', 'pink', 'prism',
2606+
'spring', 'summer', 'winter',
25392607

25402608
# classes and modules
25412609

license.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
LICENSE AGREEMENT FOR MATPLOTLIB %(version)s
1010
--------------------------------------
1111
12-
1. This LICENSE AGREEMENT is between the John D. Hunter ("JDH"), and the
12+
1. This LICENSE AGREEMENT is between John D. Hunter ("JDH"), and the
1313
Individual or Organization ("Licensee") accessing and otherwise using
1414
matplotlib software in source or binary form and its associated
1515
documentation.
@@ -20,7 +20,7 @@
2020
derivative works, distribute, and otherwise use matplotlib %(version)s
2121
alone or in any derivative version, provided, however, that JDH's
2222
License Agreement and JDH's notice of copyright, i.e., "Copyright (c)
23-
2002-2004 John D. Hunter; All Rights Reserved" are retained in
23+
2002-2005 John D. Hunter; All Rights Reserved" are retained in
2424
matplotlib %(version)s alone or in any derivative version prepared by
2525
Licensee.
2626

0 commit comments

Comments
 (0)