Skip to content

Commit

Permalink
added matshow
Browse files Browse the repository at this point in the history
svn path=/trunk/matplotlib/; revision=912
  • Loading branch information
jdh2358 committed Feb 2, 2005
1 parent 770d0a0 commit 1b29e57
Show file tree
Hide file tree
Showing 5 changed files with 129 additions and 13 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
New entries should be added at the top

2005-02-02 Incorporated Fernando's matshow

2005-02-01 Added Fernando's figure num patch, including experemental
support for pylab backend switching, LineCOllection.color
warns, savefig now a figure method, fixed a close(fig) bug
Expand Down
6 changes: 5 additions & 1 deletion TODO
Original file line number Diff line number Diff line change
Expand Up @@ -642,4 +642,8 @@ ZeroDivisionError: SeparableTransformation::eval_scalars yin interval is zero; c

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

-- port colorbar, current mappable to API
-- port colorbar, current mappable to API

-- add qt / gpl warning

-- Nil's xtick labeling bug
44 changes: 43 additions & 1 deletion lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from text import Text, _process_text_args
from legend import Legend
from transforms import Bbox, Value, Point, get_bbox_transform, unit_bbox

from numerix import array, clip


class Figure(Artist):
Expand Down Expand Up @@ -454,3 +454,45 @@ def savefig(self, *args, **kwargs):

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


def figaspect(arr):
"""
Determine the width and height for a figure that would fit array
preserving aspcect ratio. The figure width, height in inches are
returned. Be sure to create an axes with equal with and height, eg
w, h = figaspect(A)
fig = Figure(figsize=(w,h))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.imshow(A, **kwargs)
Thanks to Fernando Perez for this function
"""

# min/max sizes to respect when autoscaling. If John likes the idea, they
# could become rc parameters, for now they're hardwired.
figsize_min = array((4.0,2.0)) # min length for width/height
figsize_max = array((16.0,16.0)) # max length for width/height
#figsize_min = rcParams['figure.figsize_min']
#figsize_max = rcParams['figure.figsize_max']

# Extract the aspect ratio of the array
nr,nc = arr.shape[:2]
arr_ratio = float(nr)/nc

# Height of user figure defaults
fig_height = rcParams['figure.figsize'][1]

# New size for the figure, keeping the aspect ratio of the caller
newsize = array((fig_height/arr_ratio,fig_height))

# Sanity checks, don't drop either dimension below figsize_min
newsize /= min(1.0,*(newsize/figsize_min))

# Avoid humongous windows as well
newsize /= max(1.0,*(newsize/figsize_max))

# Finally, if we have a really funky aspect ratio, break it but respect
# the min/max dimensions (we don't want figures 10 feet tall!)
newsize = clip(newsize,figsize_min,figsize_max)
return newsize
86 changes: 77 additions & 9 deletions lib/matplotlib/pylab.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
ishold - return the hold state of the current axes
legend - make an axes legend
loglog - a log log plot
matshow - display a matrix in a new figure preserving aspect
pcolor - make a pseudocolor plot
pie - make a pie chart
plot - make a line plot
Expand Down Expand Up @@ -195,7 +196,7 @@
from cbook import flatten, is_string_like, exception_to_str, popd, silent_list, iterable
from colors import normalize
from cm import ColormapJet, Grayscale, get_cmap
from figure import Figure
from figure import Figure, figaspect
import image
from matplotlib import rcParams, rcParamsDefault, get_backend
from backend_bases import FigureCanvasBase
Expand Down Expand Up @@ -336,6 +337,7 @@ def plotting():
loglog - a log log plot
imread - load image file into array
imshow - plot image data
matshow - display a matrix in a new figure preserving aspect
pcolor - make a pseudocolor plot
plot - make a line plot
psd - make a plot of power spectral density
Expand Down Expand Up @@ -1598,6 +1600,71 @@ def switch_backend(newbackend):
from backends import new_figure_manager, error_msg, \
draw_if_interactive, show


def matshow(*args,**kw):
"""Display an array as a matrix.
The origin is set at the upper left hand corner and rows (first dimension
of the array) are displayed horizontally. The aspect ratio of the figure
window is that of the array, as long as it is possible to fit it within
the constraints of your figure.figsize_min/max parameters with no
stretching. If the window dimensions can't accomodate this (extremely
tall/wide arrays), some stretching will inevitably occur.
matshow() calls imshow() with Aargs and **kwargs, but by default
it sets interpolation='nearest' (unless you override it). All
other arguments and keywords are passed to imshow(), so see its
docstring for further details.
Tick labels for the xaxis are placed on top by default.
return value is a (fig, ax, im) tuple
Example usage:
def samplemat(dims):
aa = zeros(dims)
for i in range(min(dims)):
aa[i,i] = i
return aa
dimlist = [(12,12),(128,64),(64,512),(2048,256)]
for i, d in enumerate(dimlist):
fig, ax, im = matshow(samplemat(d))
show()
"""

arr = args[0]
w,h = figaspect(arr)
fig = figure(figsize=(w,h))
ax = fig.add_axes([0.0, 0.05, 0.8, 0.8])

ax.xaxis.tick_top()
ax.title.set_y(1.05) # raise it up a bit for tick top
# Call with 'lower' origin (we'll flip axes later)
kw['origin'] = 'lower'

# We also set a 'free' aspect ratio b/c we've already done our best to fix
# it, while preserving the dimension sanity checks. At this point, if a
# bit of rescaling is needed, so be it. Otherwise, we'd get the nasty
# white bands we're working so hard to prevent.
kw['aspect'] = 'free'

# Unless overridden, don't interpolate
kw.setdefault('interpolation','nearest')

# All other keywords go through to imshow.
im = ax.imshow(*args,**kw)

# set the x and y lim to equal the matrix dims
nr,nc = arr.shape[:2]
ax.set_xlim((0,nc))
ax.set_ylim((nr,0))
return fig, ax, im


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

__plotting_all__ = [
# plotting

'plotting', 'colormaps', 'get_current_fig_manager', 'connect',
'disconnect', 'get_plot_commands', 'raise_msg_to_str', 'axis',
'axes', 'delaxes', 'clim', 'close', 'clf', 'colorbar', 'draw',
'figtext', 'figimage', 'figlegend', 'figure', 'gca', 'gcf', 'gci',
'get', 'hold', 'ishold', 'isinteractive', 'imread', 'load', 'rc',
'rcdefaults', 'save', 'savefig', 'set', 'subplot', 'twinx', 'title',
'xlabel', 'ylabel', 'xlim', 'ylim', 'xticks', 'rgrids',
'rcdefaults', 'save', 'savefig', 'set', 'subplot', 'twinx',
'title', 'xlabel', 'ylabel', 'xlim', 'ylim', 'xticks', 'rgrids',
'thetagrids', 'yticks', 'polar', 'over', 'ioff', 'ion', 'axhline',
'axhspan', 'axvline', 'axvspan', 'bar', 'barh', 'cohere',
'contour', 'csd', 'errorbar', 'fill', 'hist', 'hlines', 'imshow',
'loglog', 'pcolor', 'pcolor_classic', 'pie', 'plot', 'plot_date',
'psd', 'scatter', 'scatter_classic', 'semilogx', 'semilogy',
'specgram', 'spy', 'spy2', 'stem', 'vlines', 'cla', 'grid',
'legend', 'table', 'text', 'autumn', 'bone', 'cool', 'copper',
'flag', 'gray', 'hot', 'hsv', 'jet', 'pink', 'prism', 'spring',
'summer', 'winter',
'loglog', 'matshow', 'pcolor', 'pcolor_classic', 'pie', 'plot',
'plot_date', 'psd', 'scatter', 'scatter_classic', 'semilogx',
'semilogy', 'specgram', 'spy', 'spy2', 'stem', 'vlines', 'cla',
'grid', 'legend', 'table', 'text', 'autumn', 'bone', 'cool',
'copper', 'flag', 'gray', 'hot', 'hsv', 'jet', 'pink', 'prism',
'spring', 'summer', 'winter',

# classes and modules

Expand Down
4 changes: 2 additions & 2 deletions license.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
LICENSE AGREEMENT FOR MATPLOTLIB %(version)s
--------------------------------------
1. This LICENSE AGREEMENT is between the John D. Hunter ("JDH"), and the
1. This LICENSE AGREEMENT is between John D. Hunter ("JDH"), and the
Individual or Organization ("Licensee") accessing and otherwise using
matplotlib software in source or binary form and its associated
documentation.
Expand All @@ -20,7 +20,7 @@
derivative works, distribute, and otherwise use matplotlib %(version)s
alone or in any derivative version, provided, however, that JDH's
License Agreement and JDH's notice of copyright, i.e., "Copyright (c)
2002-2004 John D. Hunter; All Rights Reserved" are retained in
2002-2005 John D. Hunter; All Rights Reserved" are retained in
matplotlib %(version)s alone or in any derivative version prepared by
Licensee.
Expand Down

0 comments on commit 1b29e57

Please sign in to comment.