Sameer Grover | 1 Nov 2010 08:59
Picon

Re: Multiprocessing and matplotlib

It's a backend issue:the code works with wxagg but not with gtkagg.

On 1 November 2010 00:54, Sameer Grover <sameer.grover.1@...> wrote:
> Can matplotlib be used in scripts with multiple processes, such as
> when using the multiprocessing module?
>
> I had some difficulty getting code to work in which I was carrying out
> some long computations and wanted to show intermediate results in a
> separate process so as not to interrupt the main computation. The
> problem distilled down to trying to use the multiprocessing module and
> matplotlib together. This is a code snippet which I expected to work,
> but doesn't. Is this a matplotlib issue, some intricate issue with
> GUIs and processes, or something with my understanding of the subject?
>
> Would you expect this code to work? Is there any easy workaround?
>
> from pylab import *
> import multiprocessing
> class myclass(object):
>    def plotter(self):
>        plot([1,2,3,4])
>        show()
>    def mainfunction(self):
>        a = arange(1, 10, 0.1)
>        newprocess = multiprocessing.Process(target=self.plotter)
>        newprocess.start()
>        newprocess.join()
>        plot(a, sin(a))
>        show()
> if __name__== '__main__':
(Continue reading)

Joe Kington | 1 Nov 2010 17:54
Picon
Favicon

Auto-wrapping text within a plot... Is there a simpler solution?

Hi folks,

First off, I apologize for the wall of text...

Spurred on by this Stack Overflow question, and by an itch I've been wanting to scratch lately, I put together a a callback function that (attempts, anyway) to auto-wrap text artists to the boundaries of the axis they're in.

It is often useful to have text reflow/auto-wrap within the axis boundaries during interactive use (resizing a plot with lots of labeled points, for example...).  It doesn't really need to be precise, as long as it keeps words from being fully off the figure.

A "full" gui toolkit would be a better way of handling this, but I've gotten in the habit of slapping a few callback functions onto matplotlib figures to make (simple) interactive scripts that I can share across platforms. (Lab exercises, in my case.) Having a way to make text reflow within the axis boundaries during resizing of plots makes things a bit easier.

I'm aware that this isn't really possible in a general, backend-independent fashion due to the subtleties of text rendering in matplotlib (e.g. things like latex, where the length of the raw string has nothing to do with it's rendered size, and the general fact that the size of the text isn't known until after it's drawn).    Even getting it approximately correct is still useful, though.

I have it working about as well as the approach I'm taking can do, I think, but I could use some help on a couple of points.

I have two specific questions, and one more general one...

First:

Is it possible to disconnect and then reconnect a callback function from an event within the callback function, and without disconnecting all other callback functions from the event? 

I'm redrawing the canvas within a "draw_event" callback function, and I'm currently avoiding recursion by disconnecting and reconnecting all callbacks to the draw event. It would be nice to disconnect only the function I'm inside, but I can't find any way of getting its cid...

Alternatively, is there a way to redraw a figure's canvas without triggering a draw event?

Second:
Is there any way to determine the average aspect ratio of a font in matplotlib?

I'm trying to approximate the length of a rendered text string based on it's font size and the number of characters. Currently, I'm assuming that all fonts have an average aspect ratio of 0.5, which works decently for most non-monospaced fonts, but fails miserably with others.

Finally:
Is there a better way to do this? My current approach has tons of limitations but works in most situations.  My biggest problem so far is that vertical alignment in matplotlib (quite reasonably) refers to an axis-aligned bounding box, rather than within a text aligned bounding box. This makes reflowing rotated text more difficult, and I'm only half-way dealing with rotated text in the code below.  Any suggestions on any points are welcome!

Thanks!
-Joe

import matplotlib.pyplot as plt

def main():
    fig = plt.figure()
    plt.plot(range(10))

    t = "This is a really long string that I'd rather have wrapped so that it"\
    " doesn't go outside of the figure, but if it's long enough it will go"\
    " off the top or bottom!"
    plt.text(7, 3, t, ha='center', rotation=30, va='center')
    plt.text(5, 7, t, fontsize=18, ha='center')
    plt.text(3, 0, t, family='serif', style='italic', ha='right')
    plt.title("This is a really long title that I want to have wrapped so it"\
             " does not go outside the figure boundaries")
    fig.canvas.mpl_connect('draw_event', on_draw)
    plt.show()

def on_draw(event):
    import matplotlib as mpl
    fig = event.canvas.figure

    # Cycle through all artists in all the axes in the figure
    for ax in fig.axes:
        for artist in ax.get_children():
            # If it's a text artist, wrap it...
            if isinstance(artist, mpl.text.Text):
                autowrap_text(artist, event.renderer)

    # Temporarily disconnect any callbacks to the draw event...
    # (To avoid recursion)
    func_handles = fig.canvas.callbacks.callbacks[event.name]
    fig.canvas.callbacks.callbacks[event.name] = {}
    # Re-draw the figure..
    fig.canvas.draw()
    # Reset the draw event callbacks
    fig.canvas.callbacks.callbacks[event.name] = func_handles

def autowrap_text(textobj, renderer):
    import textwrap
    from math import sin, cos
    # Get the starting position of the text in pixels...
    x0, y0 = textobj.get_transform().transform(textobj.get_position())
    # Get the extents of the current axis in pixels...
    clip = textobj.get_axes().get_window_extent()

    # Get the amount of space in the direction of rotation to the left and
    # right of x0, y0
    # (This doesn't try to correct for different vertical alignments, and will
    # have issues with rotated text when va & ha are not 'center')
    dx1, dx2 = x0 - clip.x0, clip.x1 - x0
    dy1, dy2 = y0 - clip.y0, clip.y1 - y0
    rotation = textobj.get_rotation()
    left_space = min(abs(dx1 / cos(rotation)), abs(dy1 / sin(rotation)))
    right_space = min(abs(dx2 / cos(rotation)), abs(dy2 / sin(rotation)))
 
    # Determine the width (in pixels) of the new text
    alignment = textobj.get_horizontalalignment()
    if alignment is 'left':
        new_width = right_space
    elif alignment is 'right':
        new_width = left_space
    else:
        new_width = 2 * min(left_space, right_space)

    # Estimate the width of the new size in characters...
    aspect_ratio = 0.5 # This varies with the font!!
    fontsize = textobj.get_size()
    pixels_per_char = aspect_ratio * renderer.points_to_pixels(fontsize)

    # If wrap_width is < 1, just make it 1 character
    wrap_width = max(1, new_width // pixels_per_char)
    try:
        wrapped_text = textwrap.fill(textobj.get_text(), wrap_width)
    except TypeError:
        # This appears to be a single word
        wrapped_text = textobj.get_text()
    textobj.set_text(wrapped_text)

if __name__ == '__main__':
    main()


------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store 
http://p.sf.net/sfu/nokia-dev2dev
_______________________________________________
Matplotlib-users mailing list
Matplotlib-users@...
https://lists.sourceforge.net/lists/listinfo/matplotlib-users
starz1010101 | 1 Nov 2010 19:29
Picon
Favicon

Can't force draw


I can't force pyplot to draw in the middle a function.  For example, this
function does not plot the sine before the user prompt, only after the
entire function executes:

import matplotlib.pyplot as plt
import numpy as np

def plot_now():
  plt.ion()
  plt.figure()
  x = 2*np.pi*np.linspace(0.0, 1.0, 100)
  plt.plot( x, np.sin(x) )
  plt.draw()
  plt.draw()
  q  = raw_input( 'anything: ')

I'm using the enthought python distribution for mac in ipython.  

--

-- 
View this message in context: http://old.nabble.com/Can%27t-force-draw-tp30107286p30107286.html
Sent from the matplotlib - users mailing list archive at Nabble.com.

------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store 
http://p.sf.net/sfu/nokia-dev2dev
Bartosz Telenczuk | 1 Nov 2010 20:22
Picon
Favicon

Ticks direction

Hi all,

Is it possible to set direction (in or out) individually for each tick. I know about the rc setting
("(x/y)tick.direction") , but I need a finer control over the ticks.

Thanks,

Bartek

------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store 
http://p.sf.net/sfu/nokia-dev2dev
Timothy W. Hilton | 1 Nov 2010 18:47
Picon

colormaps - combine linear segmented with discrete sections?

Hello,

I have a 2D numpy masked array of geo-located data -- with some data
missing -- that I wish to plot on a map.  Basemap provides a nice tool
to do this, but I am stumped trying to get the colorscheme I want.

My data are only physically meaningful on land, so I am using
Basemap.maskoceans() to mask out "wet" locations (oceans, lakes, etc.)
Trouble is, now both water as well as actual missing data show up in
the missing data color.

I want to have blue water, some other (bright) color for missing data,
and a nice-looking color transition (matplotlib.cm.Blues or something
similar) for the valid data over land (values from 0 to 50).  The
Cookbook example at
<http://www.scipy.org/Cookbook/Matplotlib/Plotting_Images_with_Special_Values>
addresses my problem, but I cannot get it to work.  After changing
instances of matplotlib.numerix to numpy, I get a long list of
exceptions, the last of which is 
TypeError: __call__() got an unexpected keyword argument 'bytes'.  
This has to do with sentinelNorm, I think, but I'm not sure how to fix it.

Eventually I would like to sub-classify missing data by the type of
missing input that caused a missing value, but for now a single
missing data color is enough.

The code below does almost what I want- I just need to figure out how
to make the water blue.  I have also messed around with
matplotlib.cm.BoundaryNorm to create a colormap/normalization to
handle my data, but I am getting hung up initializing the cmap,
counting bin edges, etc.  I also tacked my test code for that...  Any
help greatly appreciated!

Thanks,
Tim

--

Timothy W. Hilton
PhD Candidate, Department of Meteorology
The Pennsylvania State University
503 Walker Building, University Park, PA   16802
hilton@...

#--------------------------------------------------
# amost right...

import numpy as np
import numpy.ma as ma
from mpl_toolkits.basemap import Basemap, maskoceans
import matplotlib.pyplot as plt
import matplotlib.colors

if __name__=="__main__":

    # setup a basemap instance & draw a map
    m_aeqd = Basemap(width=9e5,height=9e5,projection='aeqd',
                     lat_0=28.46,lon_0=360-80.67, resolution='i', area_thresh=1000,
                     rsphere=6371007.181000)
    col_water='#B9D3EE'  #SlateGray2
    col_land ='#1C1C1C'
    m_aeqd.drawmapboundary(fill_color=col_water)
    # draw coasts and fill continents.
    m_aeqd.drawcoastlines(linewidth=0.5)
    m_aeqd.fillcontinents(color=col_land,lake_color=col_water, zorder=0)

    
    # create a 100 x 100 pseudodata array with valid data between 0
      and 50 and some "missing" data (less than zero)
    n=100
    X = ma.masked_less(np.random.random_integers(-1, 50, (n,n)), 0)
    plot_mid = np.mean((m_aeqd.llcrnrx, m_aeqd.urcrnrx))
    Xu, Xv = np.meshgrid(np.arange(stop=plot_mid + 500*n,
                                   start=plot_mid - 500*n, step=1000),
                         np.arange(stop=m_aeqd.urcrnry,
                                   start=m_aeqd.urcrnry - 1000*n, step=1000))
    Xlon, Xlat = m_aeqd(Xu, Xv, inverse=True)

    #setup a colormap and plot the data
    cmap = matplotlib.cm.get_cmap("Blues", 25)
    #mask oceans
    ocean_mask = maskoceans(Xlon, Xlat, X)
    #now I'm stumped how to incorporate oceans_mask into the color map
    oceans_cmap = matplotlib.colors.ListedColormap((col_land, "#000000"),
                                                   name="oceans", N=2)
    cmap.set_bad(color="#FF0000")  #show missing vals in bright red
    m_aeqd.pcolormesh(Xu, Xv, ocean_mask, cmap=cmap)
    plt.colorbar()

    #it seems like I could do another pcolormesh call with
    #ocean_mask.mask and oceans_cmap; I'd need to set the
    #transparency.  It seems like the more elegant solution is to
    #devise cmap to account for ocean_mask.mask (water) separately
    #from X.mask (data that are actually missing).  I'm not sure how
    #do that though.

------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store 
http://p.sf.net/sfu/nokia-dev2dev
John | 2 Nov 2010 10:33
Picon

NCEP Grib Definitions

Folks,

I'm trying to find documentation online that provides guidance on what
all the variables are that are in the NCEP model output grib files.
There are many NCEP models, so to be clear, I'm referring to the GFS
0.5x0.5 degree product. I was looking at this nice blog:

http://joewheatley.net/ncep-global-forecast-system/

and the files that are available here:
 ftp://ftp.ncep.noaa.gov/pub/data/nccf/com/gfs/prod

And I see this link:
http://www.nco.ncep.noaa.gov/pmb/products/gfs/

But looking at a file and the variables:
In [112]: ncep.variables.keys()
Out[112]:
['PRES_P8_L223_GLL0_avg',
 'TOZNE_P0_L200_GLL0',
 'PRES_P0_L242_GLL0',
 'HGT_P0_L100_GLL0',
 'VVEL_P0_L100_GLL0',
 'UGRD_P0_L6_GLL0',
 'HGT_P0_L7_GLL0',
 'CIN_P0_2L108_GLL0',
 'ULWRF_P8_L8_GLL0_avg',
 'PRES_P0_L109_GLL0',
(snip)

is somewhat clear in most cases, but is there a table which directly
maps these online?. Also, you can of course look at the 'long_name',
'level', and 'level_type' attributes of each variable, but I'm looking
more or less for an online table showing all this. Maybe I need to
script it quickly ;)

Thanks,
john

------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store 
http://p.sf.net/sfu/nokia-dev2dev
John | 2 Nov 2010 11:19
Picon

Re: NCEP Grib Definitions

Maybe I should also follow up on this and indicate that one variable I
really want is the Veg Type defiinitions from the files. It exists in
the file from joewheatley's example, (VGTYP_P0_L1_GGA0) but it is on a
Gaussian lat/lon grid. I've downloaded some of the gfs files from the
0.5 x 0.5 degree output, but I don't find the variable.

Thanks again!

On Tue, Nov 2, 2010 at 10:33 AM, John <washakie@...> wrote:
> Folks,
>
> I'm trying to find documentation online that provides guidance on what
> all the variables are that are in the NCEP model output grib files.
> There are many NCEP models, so to be clear, I'm referring to the GFS
> 0.5x0.5 degree product. I was looking at this nice blog:
>
> http://joewheatley.net/ncep-global-forecast-system/
>
> and the files that are available here:
>  ftp://ftp.ncep.noaa.gov/pub/data/nccf/com/gfs/prod
>
> And I see this link:
> http://www.nco.ncep.noaa.gov/pmb/products/gfs/
>
> But looking at a file and the variables:
> In [112]: ncep.variables.keys()
> Out[112]:
> ['PRES_P8_L223_GLL0_avg',
>  'TOZNE_P0_L200_GLL0',
>  'PRES_P0_L242_GLL0',
>  'HGT_P0_L100_GLL0',
>  'VVEL_P0_L100_GLL0',
>  'UGRD_P0_L6_GLL0',
>  'HGT_P0_L7_GLL0',
>  'CIN_P0_2L108_GLL0',
>  'ULWRF_P8_L8_GLL0_avg',
>  'PRES_P0_L109_GLL0',
> (snip)
>
> is somewhat clear in most cases, but is there a table which directly
> maps these online?. Also, you can of course look at the 'long_name',
> 'level', and 'level_type' attributes of each variable, but I'm looking
> more or less for an online table showing all this. Maybe I need to
> script it quickly ;)
>
> Thanks,
> john
>

-- 
Configuration
``````````````````````````
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0

------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store 
http://p.sf.net/sfu/nokia-dev2dev
Daπid | 2 Nov 2010 12:18
Picon
Gravatar

show(), the state of the art

Hello.

It is stated that show() should be the last function in a script, as
long as it will stop the execution of the program. Nevertheless, I
have seen that the current behavior is just a pause in the flow, and
it will be restored when the window is closed. The documentation says:

"Many users are frustrated by show because they want it to be a
blocking call that raises the figure, pauses the script until the
figure is closed, and then allows the script to continue running until
the next figure is created and the next show is made.[...]

This is not what show does and unfortunately, because doing blocking
calls across user interfaces can be tricky, is currently unsupported,
though we have made some progress towards supporting blocking events."

My question is: what is the real state of the art of the feature? Is
this something that could be safely exploited, or just an experimental
property not recommended?

I am using Matplotlib v.1.0 and Python 2.5 over Windows XP and TkAgg backend.

Thanks in advance.

------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store 
http://p.sf.net/sfu/nokia-dev2dev
David Kremer | 2 Nov 2010 12:49
Picon

Re: show(), the state of the art

Personally I used show() yesterday, and it blocks the execution until
the figure's window is closed. It is of perfect convenience I think,
as a default behavior.

However, I would like to add an option to show() like eg :

> show( save_image = True , format = 'eps' )

As it permits to mix the two behavior : interrupt script execution and
let the execution be continued if the user decides so.

I don't know if it's possible, but I would like it be.

Kind regards.

David

2010/11/2 Daπid <davidmenhur <at> gmail.com>:
> Hello.
>
> It is stated that show() should be the last function in a script, as
> long as it will stop the execution of the program. Nevertheless, I
> have seen that the current behavior is just a pause in the flow, and
> it will be restored when the window is closed. The documentation says:
>
>
> "Many users are frustrated by show because they want it to be a
> blocking call that raises the figure, pauses the script until the
> figure is closed, and then allows the script to continue running until
> the next figure is created and the next show is made.[...]
>
> This is not what show does and unfortunately, because doing blocking
> calls across user interfaces can be tricky, is currently unsupported,
> though we have made some progress towards supporting blocking events."
>
> My question is: what is the real state of the art of the feature? Is
> this something that could be safely exploited, or just an experimental
> property not recommended?
>
>
> I am using Matplotlib v.1.0 and Python 2.5 over Windows XP and TkAgg backend.
>
>
> Thanks in advance.
>
> ------------------------------------------------------------------------------
> Nokia and AT&T present the 2010 Calling All Innovators-North America contest
> Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
> $10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
> Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store
> http://p.sf.net/sfu/nokia-dev2dev
> _______________________________________________
> Matplotlib-users mailing list
> Matplotlib-users <at> lists.sourceforge.net
> https://lists.sourceforge.net/lists/listinfo/matplotlib-users
>

------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store 
http://p.sf.net/sfu/nokia-dev2dev
_______________________________________________
Matplotlib-users mailing list
Matplotlib-users <at> lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Michael Droettboom | 2 Nov 2010 13:45

Re: show(), the state of the art

On 11/02/2010 07:49 AM, David Kremer wrote:
> Personally I used show() yesterday, and it blocks the execution until
> the figure's window is closed. It is of perfect convenience I think,
> as a default behavior.
>
> However, I would like to add an option to show() like eg :
>
>    
>> show( save_image = True , format = 'eps' )
>>      
Do you mean this to do what savefig() already does?

Mike

--

-- 
Michael Droettboom
Science Software Branch
Space Telescope Science Institute
Baltimore, Maryland, USA

------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store 
http://p.sf.net/sfu/nokia-dev2dev

Gmane