Help with simply plotting 2d array, please

Hello all, I've been trying for days but I can't seem to get the
result I'm looking for. I have a 2d array of type "numpy.ndarray"
which I'd like to plot as a simple color map. I'd like to plot it in
the upper-lefthand corner of the client area in a wxPython frame. The
plotting needs to be a very simple 1:1 ratio, for example if the numpy
array has 400 rows and 500 columns, I would like to plot it so that it
assumes 400x500 pixels in the wxPython frame. I do not need axis ticks
and labels, just the colormap plot itself. I can get my figure to plot
(with tick marks and labels since I haven't figured out how to turn
those off) but I cannot size it properly. I've copied a tutorial
example I found and modify it and through tedious trial and error have
gotten half-way to where I need:

# First attempt to render data to a window:

import matplotlib
matplotlib.use('WXAgg')

from matplotlib import rcParams
import numpy

import matplotlib.cm as cm

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg

#from matplotlib.figure import Figure

from wx import *

import DataFileTypes as DFT

class DataFrame(Frame):

    def __init__(self):

        Frame.__init__(self, None, -1, "Data filename here",
                       size=DisplaySize())

    def displayData(self):

        data = None

        # Load data into "data" object using my custom IntData(...) class:
        try:
            data = DFT.INTData("C:\SAR Test files\Tibet2008.int")

        except DFT.DataFileError:
            print("Error opening data file")

        except DFT.ResourceFileError:
            print("Error opening resource file")

        if data:

            # Assume a screen dpi of 96...seems very flakey to me:
            ScreenDPI = 96.0

            # compute the width and height of figure using this dpi
            # and the rows and columns of the data for a 1:1 display ratio:
            FigureWidthInInches = (data.numcolumns / ScreenDPI)
            FigureHeightInInches = (data.numrows / ScreenDPI)
            print(FigureWidthInInches, FigureHeightInInches)

            # Instantiate Figure based on these parameters:
            self.fig =
matplotlib.figure.Figur((FigureWidthInInches,FigureHeightInInches),
dpi = ScreenDPI)
            self.canvas = FigureCanvasWxAgg(self, -1, self.fig)

            # Put everything into a sizer:
            sizer = BoxSizer(VERTICAL)
            #sizer.Add(self.canvas, 1, LEFT | TOP | GROW)
            sizer.Add(self.canvas, 0, LEFT | TOP)
            self.SetSizer(sizer)
            # self.Fit()

            a = self.fig.add_axes([0.075, 0.1, 0.75, 0.85])
            self.im = a.imshow(data.getNumpyArray(),
interpolation=None, cmap = data.getCustomColorMap())

if __name__ == '__main__':

    app = PySimpleApp()
    frame = DataFrame()
    frame.displayData()

    frame.Show()
    app.MainLoop()

It displays but the plot is inside the figure i.e. the colormap of the
data is within the figure that I've sized. matplotlib does this by
design, of course, but I cannot figure out how to defeat it. For one
thing, I don't think I'm sizing the figure correctly by setting
(guessing at) the dpi and computing the inches...just seems wrong, but
I can't find any tutorials or examples that show anything that sizes
figures using pixels or screen coords.

I always know the dimensions of my data a priori, so let's assume the
following very simple situation:

- I have a numpy.ndarray of data with 350 rows and 500 columns. How do
I display it in the upper-left hand corner of the frame client with no
tick marks/labels, etc...just the colormap at screen
coords(0,0)->(349,499) (rows,columns)? Could someone post a few lines
to do this? Thanks so much in advance!

-L

LKeene wrote:

- I have a numpy.ndarray of data with 350 rows and 500 columns. How do
I display it in the upper-left hand corner of the frame client with no
tick marks/labels, etc...just the colormap at screen
coords(0,0)->(349,499) (rows,columns)? Could someone post a few lines
to do this? Thanks so much in advance!

-L

Hmm... interesting problem...

Here's a simple example where the image fills the frame - note the
properties such as xticks, yticks = [], position=[0,0,1,1], and the size of
the Frame itself... on my platform (Mac OS X) the height of the frame should
be 22 pixels more than the image (discovered by trial and error).

The border of the axes is still visible in black - obscuring the outer
pixels of the image - does anyone know how to shut that off?

import matplotlib
matplotlib.interactive(False)
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.figure import Figure
from matplotlib.pyplot import setp

import numpy as np

import wx

class MatplotlibFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.figure = Figure()
        print self.figure
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure)

        self.subplot = self.figure.add_subplot(111)
        #cdata = np.random.rand(351, 501)
        cdata = np.zeros((351, 501))
        cdata[::50, ::50] = 1
        self.subplot.imshow(cdata, aspect='equal', interpolation='nearest')
        setp(self.subplot, xticks=[], yticks=[], position=[0,0,1,1])

    def repaint(self):
        self.canvas.draw()

class App(wx.App):
    def OnInit(self):
        frame = MatplotlibFrame(parent=None, title="an image", size=(501,
351+22))
        frame.Show()
        return True

app = App()
app.MainLoop()

···

--
View this message in context: http://www.nabble.com/Help-with-simply-plotting-2d-array%2C-please-tp22214482p22216497.html
Sent from the matplotlib - users mailing list archive at Nabble.com.

I don't use wx so i'm not sure if this could be helpful, but you may
check the figimage command.

http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.figimage

Note that it draws the image directly into the figure, thus no axes is needed.

-JJ

···

On Wed, Feb 25, 2009 at 6:09 PM, lionel keene <lionel.keene@...287...> wrote:

Hello all, I've been trying for days but I can't seem to get the
result I'm looking for. I have a 2d array of type "numpy.ndarray"
which I'd like to plot as a simple color map. I'd like to plot it in
the upper-lefthand corner of the client area in a wxPython frame. The
plotting needs to be a very simple 1:1 ratio, for example if the numpy
array has 400 rows and 500 columns, I would like to plot it so that it
assumes 400x500 pixels in the wxPython frame. I do not need axis ticks
and labels, just the colormap plot itself. I can get my figure to plot
(with tick marks and labels since I haven't figured out how to turn
those off) but I cannot size it properly. I've copied a tutorial
example I found and modify it and through tedious trial and error have
gotten half-way to where I need:

# First attempt to render data to a window:

import matplotlib
matplotlib.use('WXAgg')

from matplotlib import rcParams
import numpy

import matplotlib.cm as cm

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg

#from matplotlib.figure import Figure

from wx import *

import DataFileTypes as DFT

class DataFrame(Frame):

def __init__(self):

   Frame\.\_\_init\_\_\(self, None, \-1, &quot;Data filename here&quot;,
                  size=DisplaySize\(\)\)

def displayData(self):

   data = None

   \# Load data into &quot;data&quot; object using my custom IntData\(\.\.\.\) class:
   try:
       data = DFT\.INTData\(&quot;C:\\SAR Test files\\Tibet2008\.int&quot;\)

   except DFT\.DataFileError:
       print\(&quot;Error opening data file&quot;\)

   except DFT\.ResourceFileError:
       print\(&quot;Error opening resource file&quot;\)

   if data:

       \# Assume a screen dpi of 96\.\.\.seems very flakey to me:
       ScreenDPI = 96\.0

       \# compute the width and height of figure using this dpi
       \# and the rows and columns of the data for a 1:1 display ratio:
       FigureWidthInInches  = \(data\.numcolumns / ScreenDPI\)
       FigureHeightInInches = \(data\.numrows / ScreenDPI\)
       print\(FigureWidthInInches, FigureHeightInInches\)

       \# Instantiate Figure based on these parameters:
       self\.fig =

matplotlib.figure.Figur((FigureWidthInInches,FigureHeightInInches),
dpi = ScreenDPI)
self.canvas = FigureCanvasWxAgg(self, -1, self.fig)

       \# Put everything into a sizer:
       sizer = BoxSizer\(VERTICAL\)
       \#sizer\.Add\(self\.canvas, 1, LEFT | TOP | GROW\)
       sizer\.Add\(self\.canvas, 0, LEFT | TOP\)
       self\.SetSizer\(sizer\)
       \# self\.Fit\(\)

       a = self\.fig\.add\_axes\(\[0\.075, 0\.1, 0\.75, 0\.85\]\)
       self\.im = a\.imshow\(data\.getNumpyArray\(\),

interpolation=None, cmap = data.getCustomColorMap())

if __name__ == '__main__':

app = PySimpleApp()
frame = DataFrame()
frame.displayData()

frame.Show()
app.MainLoop()

It displays but the plot is inside the figure i.e. the colormap of the
data is within the figure that I've sized. matplotlib does this by
design, of course, but I cannot figure out how to defeat it. For one
thing, I don't think I'm sizing the figure correctly by setting
(guessing at) the dpi and computing the inches...just seems wrong, but
I can't find any tutorials or examples that show anything that sizes
figures using pixels or screen coords.

I always know the dimensions of my data a priori, so let's assume the
following very simple situation:

- I have a numpy.ndarray of data with 350 rows and 500 columns. How do
I display it in the upper-left hand corner of the frame client with no
tick marks/labels, etc...just the colormap at screen
coords(0,0)->(349,499) (rows,columns)? Could someone post a few lines
to do this? Thanks so much in advance!

-L

------------------------------------------------------------------------------
Open Source Business Conference (OSBC), March 24-25, 2009, San Francisco, CA
-OSBC tackles the biggest issue in open source: Open Sourcing the Enterprise
-Strategies to boost innovation and cut costs with open source participation
-Receive a $600 discount off the registration fee with the source code: SFAD
http://p.sf.net/sfu/XcvMzF8H
_______________________________________________
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users