Re: [Matplotlib-users] How to Reduce White Space Around Figure?

2010-10-25 Thread Tony S Yu

On Oct 25, 2010, at 12:56 PM, Lorenzo Isella wrote:

 Dear All,
 I am aware that this question has already been asked several times on 
 the mailing list, see e.g.
 
 http://bit.ly/aPzQTA
 
 However, in the following snippet, nothing I tried has been able to 
 reduce the amount of white space around the figure (including toying 
 around with
 
 ax = plt.axes([0.0, 0.0, 1.0, 1.0])
 )
 Of course, one can always resort to pdfcrop, but I believe there must be 
 a better solution to resize the margins from matplotlib.
 Please see the snippet at the end of the email.
 Every suggestion is welcome.
 Cheers
 
 Lorenzo

[cut out code snippet]

You can always use subplots_adjust. I haven't looked into the details of your 
code, but it appears as though the actual plot (the actual graphics) is well 
within the margins of your subplot (extending the boundaries of the subplot 
would still leave a lot of white space). To counteract this you can use 
negative padding (and padding greater than 1); e.g.

subplots_adjust(top=1, bottom=-0.2, left=-0.3, right=1.3)

(you can add this right before savefig.) This means that the actual 
boundaries of the subplot extend outside the figure (which normally have 
extents from 0 to 1). The above gives pretty good results. To get any better, I 
think you need to adjust the aspect ratio of the figure to match the plot (you 
can do this by creating a figure and passing a value for figsize).

-Tony

P.S. since you posted code, I'll offer an unsolicited suggestion. :) You can 
replace all your annotate commands (except for the last 2) with two short loops:

for y in np.arange(-1.4, 1.5, 0.2):
annotate(, xy=(-pi/2., y), xytext=(-ini, y), arrowprops=dict(fc=g))
for y in np.arange(-1.4, 1.5, 0.2):
annotate(, xy=(pi/2., y), xytext=(ini, y), arrowprops=dict(fc=g))


--
Nokia and ATT 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@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Graph

2010-10-08 Thread Tony S Yu

On Oct 8, 2010, at 6:52 AM, Waléria Antunes David wrote:

 I don't understand what you did, i'm reading error data from a file.
 
 def gera_grafico(N=200, eps=1):
 
 x = np.abs(np.random.randn(N))
 y = 10*np.log((30*x + 1.)**(0.5)) + 34 + eps * np.random.randn(N)
 yerr = eps * np.random.randn(N)
 
 I don't understand what you did in this code
 
 ??
 
 Thanks,
 Waleria.

Hey Waleria,

That was just some code to make up fake data with roughly the same shape and 
range as the data you plotted. As I mentioned, I needed to put something there 
to run your code.

Where do you get an error? If it's from the code above, you can just replace it 
with your data. In any case, you don't need to use the code I pasted; just make 
the changes I suggested: Fix the number passed to majorLocator and remove (or 
fix the initialization of) majorFormatter.

-T

 
 
 On Thu, Oct 7, 2010 at 5:06 PM, Tony S Yu tsy...@gmail.com wrote:
 
 On Oct 7, 2010, at 3:38 PM, Waléria Antunes David wrote:
 
 Hi,
 
 I did like the links below, but seeing as it was my chart.
 
 See
 
 My code: http://pastebin.com/KcjHAPLN
 
 On Thu, Oct 7, 2010 at 3:08 PM, John Hunter jdh2...@gmail.com wrote:
 On Thu, Oct 7, 2010 at 1:01 PM, Waléria Antunes David
 waleriantu...@gmail.com wrote:
  I need to know how do these vertical lines on the graph. See the picture,
  the lines circled.
 
 We call these major and minor ticks.  The major ticks are the taller
 ones, the minor ticks are the smaller ones.  Their location is
 controlled by the major and minor Locator instances, and the text
 printed beside them is controlled by the major and minor formatter.
 
 See
 
  
 http://matplotlib.sourceforge.net/examples/pylab_examples/major_minor_demo1.html
  
 http://matplotlib.sourceforge.net/examples/pylab_examples/major_minor_demo2.html
 
 and
 
  http://matplotlib.sourceforge.net/search.html?q=codex+set_minor_locator
 
 To control the tick properties themselves, see the Tick section in
 
  http://matplotlib.sourceforge.net/users/artists.html
 
 JDH
 
 graph.png
 
 As John mentioned, the major and minor ticks were the taller and shorter 
 ticks, respectively. In your pasted example, you only change the minor ticks; 
 by setting the majorLocator to same value as in the original example (i.e. 
 20), you only get the major tick at 0 because your data only goes to 1.5 
 (i.e. 20 is outside your plot range).
 
 Also, the majorFormatter in the example is set to work with integers, but 
 your major tick labels should be float values (since most of them are between 
 0 and 1). Thus, the majorFormatter code is unnecessary (commented out below).
 
 Finally, a pet peeve: when posting example code, please make the effort to 
 generate data for the plot so that others can easily run the code (see 
 attached).
 
 -Tony
 
 #---
 
 import numpy as np
 import matplotlib.pyplot as plt
 from matplotlib.ticker import MultipleLocator, FormatStrFormatter
 
 def gera_grafico(N=200, eps=1):
 
 x = np.abs(np.random.randn(N))
 y = 10*np.log((30*x + 1.)**(0.5)) + 34 + eps * np.random.randn(N)
 yerr = eps * np.random.randn(N)
 
 majorLocator   = MultipleLocator(0.2)
 # majorFormatter = FormatStrFormatter('%d')
 minorLocator   = MultipleLocator(0.02)
 
 fig, ax = plt.subplots()
 plt.errorbar(x, y, yerr, fmt='ob', label='date')
 
 plt.xlim(0.0, 1.5)
 #plt.xscale('log')
 #grid(True)
 
 ax.xaxis.set_major_locator(majorLocator)
 # ax.xaxis.set_major_formatter(majorFormatter)
 
 ax.xaxis.set_minor_locator(minorLocator)
 
 return fig
 
 if __name__ == '__main__':
 gera_grafico()
 plt.show()
 
 
 

--
Beautiful is writing same markup. Internet Explorer 9 supports
standards for HTML5, CSS3, SVG 1.1,  ECMAScript5, and DOM L2  L3.
Spend less time writing and  rewriting code and more time creating great
experiences on the web. Be a part of the beta today.
http://p.sf.net/sfu/beautyoftheweb___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Graph

2010-10-07 Thread Tony S Yu

On Oct 7, 2010, at 11:54 AM, Waléria Antunes David wrote:

 Hi,
 
 I'm asking how to have only the vertical grid lines.?
 And I'm trying to increase the spacing in the x direction, I used the 
 'ax.set_xscale (' log ')', but the points were even more confused.
 Do you saw my image that sent yestarday?
 
 Thanks,
 Waleria


I have to agree with Ben that your description is a little confusing. Looking 
at the plot you posted, I'm not sure what part of the plot you're interested in 
reproducing. I don't see any vertical lines; do you mean the vertical layout 
of the plot itself? If that's the case you can set the figure size such that it 
is taller than it is wide. For example, before creating your plot you can call: 

 import matplotlib.pyplot as plt
 plt.figure(figsize=(6, 8))

But from your original question, it sounds like you want the opposite, since a 
wider plot would stretch the x-distance between data points (logspacing 
stretches distances for low values, but maybe you want to stretch the distance 
for all values?). In this case you could just increase the width of the figure; 
for example:

 plt.figure(figsize=(12, 6))

This may not fit on your screen, though. If you're working interactively (with 
plt.show instead of plt.savefig) you can just resize the window to your liking.

-T


 On Wed, Oct 6, 2010 at 5:10 PM, Benjamin Root ben.r...@ou.edu wrote:
 
 
 On Wed, Oct 6, 2010 at 2:36 PM, Waléria Antunes David 
 waleriantu...@gmail.com wrote:
 Benjamin,
 
 I used the 'ax.set_xscale (' log ')', but the points were even more confused. 
 What I need is to increase from 0.0 to 0.2 points, 0.2 to 0.4 ... increase 
 the size of the graph. However I do not know if the chart is well visualized 
 on a monitor 20''.?
 
 
 Are you trying to increase the spacing in the x direction or the y direction? 
  Log scaling is a standard trick to achieve this effect.
  
 And how do I let my chart like this: 
 http://www.supernova.lbl.gov/PDFs/SCP2003SNeCMBClust.pdf
 This graph format with vertical line on, something like that.
 
 
 Are you asking how to add a vertical line to your graph, or how to have only 
 the vertical grid lines?
 
 Ben Root
 
 
 --
 Beautiful is writing same markup. Internet Explorer 9 supports
 standards for HTML5, CSS3, SVG 1.1,  ECMAScript5, and DOM L2  L3.
 Spend less time writing and  rewriting code and more time creating great
 experiences on the web. Be a part of the beta today.
 http://p.sf.net/sfu/beautyoftheweb___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

--
Beautiful is writing same markup. Internet Explorer 9 supports
standards for HTML5, CSS3, SVG 1.1,  ECMAScript5, and DOM L2  L3.
Spend less time writing and  rewriting code and more time creating great
experiences on the web. Be a part of the beta today.
http://p.sf.net/sfu/beautyoftheweb___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Graph

2010-10-07 Thread Tony S Yu

On Oct 7, 2010, at 3:38 PM, Waléria Antunes David wrote:

 Hi,
 
 I did like the links below, but seeing as it was my chart.
 
 See
 
 My code: http://pastebin.com/KcjHAPLN
 
 On Thu, Oct 7, 2010 at 3:08 PM, John Hunter jdh2...@gmail.com wrote:
 On Thu, Oct 7, 2010 at 1:01 PM, Waléria Antunes David
 waleriantu...@gmail.com wrote:
  I need to know how do these vertical lines on the graph. See the picture,
  the lines circled.
 
 We call these major and minor ticks.  The major ticks are the taller
 ones, the minor ticks are the smaller ones.  Their location is
 controlled by the major and minor Locator instances, and the text
 printed beside them is controlled by the major and minor formatter.
 
 See
 
  
 http://matplotlib.sourceforge.net/examples/pylab_examples/major_minor_demo1.html
  
 http://matplotlib.sourceforge.net/examples/pylab_examples/major_minor_demo2.html
 
 and
 
  http://matplotlib.sourceforge.net/search.html?q=codex+set_minor_locator
 
 To control the tick properties themselves, see the Tick section in
 
  http://matplotlib.sourceforge.net/users/artists.html
 
 JDH
 
 graph.png

As John mentioned, the major and minor ticks were the taller and shorter ticks, 
respectively. In your pasted example, you only change the minor ticks; by 
setting the majorLocator to same value as in the original example (i.e. 20), 
you only get the major tick at 0 because your data only goes to 1.5 (i.e. 20 is 
outside your plot range).

Also, the majorFormatter in the example is set to work with integers, but your 
major tick labels should be float values (since most of them are between 0 and 
1). Thus, the majorFormatter code is unnecessary (commented out below).

Finally, a pet peeve: when posting example code, please make the effort to 
generate data for the plot so that others can easily run the code (see 
attached).

-Tony

#---

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

def gera_grafico(N=200, eps=1):

x = np.abs(np.random.randn(N))
y = 10*np.log((30*x + 1.)**(0.5)) + 34 + eps * np.random.randn(N)
yerr = eps * np.random.randn(N)

majorLocator   = MultipleLocator(0.2)
# majorFormatter = FormatStrFormatter('%d')
minorLocator   = MultipleLocator(0.02)

fig, ax = plt.subplots()
plt.errorbar(x, y, yerr, fmt='ob', label='date')

plt.xlim(0.0, 1.5)
#plt.xscale('log')
#grid(True)

ax.xaxis.set_major_locator(majorLocator)
# ax.xaxis.set_major_formatter(majorFormatter)

ax.xaxis.set_minor_locator(minorLocator)

return fig

if __name__ == '__main__':
gera_grafico()
plt.show()


--
Beautiful is writing same markup. Internet Explorer 9 supports
standards for HTML5, CSS3, SVG 1.1,  ECMAScript5, and DOM L2  L3.
Spend less time writing and  rewriting code and more time creating great
experiences on the web. Be a part of the beta today.
http://p.sf.net/sfu/beautyoftheweb___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] unicode minus sign glyph missing with serif fonts in macosx backend

2010-10-04 Thread Tony S Yu

On Oct 4, 2010, at 2:56 PM, Jouni K. Seppänen wrote:

 Joey Richards j...@caltech.edu writes:
 
 When I plot with the MacOSX backend using a serif font, the negative
 signs on the axis labels show up as the missing glyph open squares
 rather than minus signs.
 
 I am using matplotlib 1.0 installed from the dmg file for Python 2.6
 on OSX 10.6.  I'm using Python 2.6.6 installed from the python.org
 binary distribution.
 
 FWIW, I can't reproduce this on OS X 10.6.4, system Python 2.6.1,
 self-compiled trunk matplotlib, tried Vera and Times New Roman.

This is probably unrelated, but I can't even use serif fonts on the MacOSX 
backend (it just shows up as sans-serif). I tried Times New Roman, Vera, and a 
Computer Modern unicode font that I normally use).

In contrast, serif fonts work fine with TkAgg and Qt4Agg on my system (OS X 
10.6.4, system Python 2.6.1, matplotlib trunk).

-Tony
--
Virtualization is moving to the mainstream and overtaking non-virtualized
environment for deploying applications. Does it make network security 
easier or more difficult to achieve? Read this whitepaper to separate the 
two and get a better understanding.
http://p.sf.net/sfu/hp-phase2-d2d
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] unicode minus sign glyph missing with serif fonts in macosx backend

2010-10-04 Thread Tony S Yu

On Oct 4, 2010, at 3:14 PM, Jouni K. Seppänen wrote:

 Tony S Yu tsy...@gmail.com writes:
 
 This is probably unrelated, but I can't even use serif fonts on the
 MacOSX backend (it just shows up as sans-serif). I tried Times New
 Roman, Vera, and a Computer Modern unicode font that I normally use).
 
 I noticed that I didn't really get Vera either, probably because I don't
 have it installed via the usual OS X way, and the MacOSX backend only
 uses fonts that it can find via CTFontCreateWithName or
 ATSFontFindFromPostScriptName, depending on the OS X version it's
 compiled for. Do you see these fonts in Font Book?

Both Times New Roman and CMU show up in Font Book. (There's also a Bitstream 
Vera font there, but it's different from the one Matplotlib uses.)

Like I said, this is probably a separate issue. I don't want to distract from 
the issue Joey raised---especially since I don't normally use the MacOSX 
backend.

-Tony
--
Virtualization is moving to the mainstream and overtaking non-virtualized
environment for deploying applications. Does it make network security 
easier or more difficult to achieve? Read this whitepaper to separate the 
two and get a better understanding.
http://p.sf.net/sfu/hp-phase2-d2d
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Combination of a box plot and a histogram

2010-10-04 Thread Tony S Yu

On Oct 4, 2010, at 4:09 PM, Friedrich Romstedt wrote:

 
 First attempt at a histogram strip chart (made up name).
 if-main block taken from [1] except that I've replaced uniform distributions
 with normal distributions.
 [1] 
 http://matplotlib.sourceforge.net/examples/pylab_examples/boxplot_demo3.html
 
 import numpy as np
 import matplotlib.pyplot as plt
 from matplotlib import collections
 
 NORM_TYPES = dict(max=max, sum=sum)
 class BinCollection(collections.PatchCollection):
 def __init__(self, hist, bin_edges, x=0, width=1, cmap=plt.cm.gray_r,
  norm_type='max', **kwargs):
 yy = (bin_edges[:-1] + bin_edges[1:])/2.
 heights = np.diff(bin_edges)
 bins = [plt.Rectangle((x, y), width, h) for y, h in zip(yy, heights)]
 norm = NORM_TYPES[norm_type]
 fc = cmap(np.asarray(hist, dtype=float)/norm(hist))
 
 super(BinCollection, self).__init__(bins, facecolors=fc, **kwargs)
 
 Is this equivalent to writing collections.PatchCollection.__init__()
 and what are the advantages of super()?

I believe collections.PatchCollection.__init__() is equivalent. In this 
instance, I don't think there are advantages (or disadvantages) to using 
super---it's just how I'm used to writing classes.

 I think you can use axes.pcolor() to replace BinCollection.  pcolor()
 just adds a collection similar to what you do now by hand for you.
 With appropriate arguments it should do the job.  You can also look
 into pcolorfast() and pcolormesh().

Yes, you're right. This was actually my main question in the original post; 
i.e. what plotting function to start with. I'm not really sure how I overlooked 
pcolor(mesh) as a viable option. Thanks.

 
 def histstrip(x, positions=None, widths=None, ax=None):
 if ax is None:
 ax = plt.gca()
 if positions is None:
 positions = range(1, len(x) + 1)
 if widths is None:
 widths = np.min(np.diff(positions)) / 2. * np.ones(len(positions))
 for data, x_pos, w in zip(x, positions, widths):
 x_pos -= w/2.
 hist, bin_edges = np.histogram(data)
 
 No other arguments to numpy.histogram() allowed?

As I mentioned, this was just a function I hacked together. I didn't try to 
make it general purpose (yet).

 
 In my opinion this is too special to be added as a general matplotlib
 plotting feature.

I'd agree that it's pretty specialized; especially since I haven't been able to 
find any mention of it. I'm still curious if there's a name for this type of 
plot if anyone out there knows.

Best,
-Tony

 
 Friedrich


--
Virtualization is moving to the mainstream and overtaking non-virtualized
environment for deploying applications. Does it make network security 
easier or more difficult to achieve? Read this whitepaper to separate the 
two and get a better understanding.
http://p.sf.net/sfu/hp-phase2-d2d
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Combination of a box plot and a histogram

2010-10-04 Thread Tony S Yu

On Oct 4, 2010, at 4:30 PM, John Hunter wrote:

 On Thu, Sep 30, 2010 at 8:44 PM, Tony S Yu tsy...@gmail.com wrote:
 I'd like to make something in between a box plot [1] and a histogram. Each 
 histogram would be represented by a single, tall, rectangular patch (like 
 the box in a box plot), and the patch would be subdivided by the bin edges 
 of the histogram. The face color of each sub-patch would replace the bar 
 height in the histogram.
 
 If any of that actually made sense:
 
 * Does this type of plot have a name?
 
 * Is there an easy way to do this in Matplotlib?
 
 * If there isn't an easy way, what would be a good starting point? Initial 
 ideas: 1) Use pcolor or imshow and embed this axes in a larger axes, 2) 
 represent the sub-patches as a PolyCollection.
 
 If you don't need faceting (dark edges around the bins), imshow with
 the extent set would be the easiest way.  If you want faceting, pcolor
 should work as well.

Thanks! I'll give both imshow and pcolor a try. Most likely I'll use pcolor, 
since lighter bins would completely disappear without faceting (... or maybe 
that's a good thing).

-Tony
--
Virtualization is moving to the mainstream and overtaking non-virtualized
environment for deploying applications. Does it make network security 
easier or more difficult to achieve? Read this whitepaper to separate the 
two and get a better understanding.
http://p.sf.net/sfu/hp-phase2-d2d
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Combination of a box plot and a histogram

2010-10-01 Thread Tony S Yu
On Oct 1, 2010, at 9:40 AM, Benjamin Root wrote:On Thu, Sep 30, 2010 at 8:44 PM, Tony S Yu tsy...@gmail.com wrote:

I'd like to make something in between a box plot [1] and a histogram. Each histogram would be represented by a single, tall, rectangular patch (like the box in a box plot), and the patch would be subdivided by the bin edges of the histogram. The face color of each sub-patch would replace the bar height in the histogram.



If any of that actually made sense:

* Does this type of plot have a name?

* Is there an easy way to do this in Matplotlib?

* If there isn't an easy way, what would be a good starting point? Initial ideas: 1) Use pcolor or imshow and embed this axes in a larger axes, 2) represent the sub-patches as a PolyCollection.

Thoughts?
-Tony

[1] e.g. http://matplotlib.sourceforge.net/examples/pylab_examples/boxplot_demo.htmlTony,

I am not quite sure I understand. [snip]Or maybe something else in the gallery is more like what you want:

http://matplotlib.sourceforge.net/gallery.htmlBen Root
I've checked the gallery, but I don't see anything that appears similar. In any case, I ended up hacking together something that works. I've attached an image of what I had in mind (created with the code at the very bottom of this reply).I ended up using mpl Rectangle objects and stringing them together using a PatchCollection. Maybe there's a more efficient way to do this, but this approach worked well-enough.Best,-Tony"""First attempt at a histogram strip chart (made up name).if-main block taken from [1] except that I've replaced uniform distributionswith normal distributions.[1] http://matplotlib.sourceforge.net/examples/pylab_examples/boxplot_demo3.html"""import numpy as npimport matplotlib.pyplot as pltfrom matplotlib import collectionsNORM_TYPES = dict(max=max, sum=sum)class BinCollection(collections.PatchCollection): def __init__(self, hist, bin_edges, x=0, width=1, cmap=plt.cm.gray_r,norm_type='max', **kwargs):   yy = (bin_edges[:-1] + bin_edges[1:])/2.   heights = np.diff(bin_edges)   bins = [plt.Rectangle((x, y), width, h) for y, h in zip(yy, heights)]   norm = NORM_TYPES[norm_type]   fc = cmap(np.asarray(hist, dtype=float)/norm(hist))   super(BinCollection, self).__init__(bins, facecolors=fc, **kwargs)def histstrip(x, positions=None, widths=None, ax=None): if ax is None:   ax = plt.gca() if positions is None:   positions = range(1, len(x) + 1) if widths is None:   widths = np.min(np.diff(positions)) / 2. * np.ones(len(positions)) for data, x_pos, w in zip(x, positions, widths):   x_pos -= w/2.   hist, bin_edges = np.histogram(data)   bins = BinCollection(hist, bin_edges, width=w, x=x_pos)   ax.add_collection(bins, autolim=True) ax.set_xticks(positions) ax.autoscale_view()if __name__ == '__main__': import matplotlib.pyplot as plt import numpy as np np.random.seed(2) inc = 0.1 e1 = np.random.normal(0,1, size=(500,)) e2 = np.random.normal(0,1, size=(500,)) e3 = np.random.normal(0,1 + inc, size=(500,)) e4 = np.random.normal(0,1 + 2*inc, size=(500,)) treatments = [e1,e2,e3,e4] fig, ax = plt.subplots() pos = np.array(range(len(treatments)))+1 histstrip(treatments, ax=ax) ax.set_xlabel('treatment') ax.set_ylabel('response') fig.subplots_adjust(right=0.99,top=0.99) plt.show()--
Start uncovering the many advantages of virtual appliances
and start using them to simplify application deployment and
accelerate your shift to cloud computing.
http://p.sf.net/sfu/novell-sfdev2dev___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] Combination of a box plot and a histogram

2010-09-30 Thread Tony S Yu
I'd like to make something in between a box plot [1] and a histogram. Each 
histogram would be represented by a single, tall, rectangular patch (like the 
box in a box plot), and the patch would be subdivided by the bin edges of the 
histogram. The face color of each sub-patch would replace the bar height in the 
histogram.

If any of that actually made sense: 

* Does this type of plot have a name?

* Is there an easy way to do this in Matplotlib?

* If there isn't an easy way, what would be a good starting point? Initial 
ideas: 1) Use pcolor or imshow and embed this axes in a larger axes, 2) 
represent the sub-patches as a PolyCollection.

Thoughts?
-Tony

[1] e.g. 
http://matplotlib.sourceforge.net/examples/pylab_examples/boxplot_demo.html
--
Start uncovering the many advantages of virtual appliances
and start using them to simplify application deployment and
accelerate your shift to cloud computing.
http://p.sf.net/sfu/novell-sfdev2dev
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] axis labels clipped

2010-09-17 Thread Tony S Yu

On Sep 17, 2010, at 8:58 AM, Erik Janssens wrote:

 Hi,
 
 I'm using matplotlib in a pyqt context, as described
 in the book 'Matplotlib for python developers'.
 
 When the window is large enough, everything works
 fine, but when the window is too small part of
 the x-axis labels get chopped.
 
 Is there a way to prevent this ?  Preferable
 in combination with the user being able to
 resize the window.
 
 Thanks a lot,
 
 Erik


Hi Erik,

Last I checked there was nothing automatic for adjusting the spacing around 
subplots. You can do so manually using ``plt.subplots_adjust`` (see for 
example, 
http://matplotlib.sourceforge.net/examples/pylab_examples/subplots_adjust.html).

A while back, I wrote some functions to calculate a good set of parameters for 
subplots_adjust (see attached; examples in if-main block at bottom). I've been 
using these functions pretty regularly, and it works pretty well for my 
purposes. 

Best,
-Tony

Some usage notes:

The function has to draw the figure a couple of times to calculate correct 
spacing. When redrawing the figure (e.g. when you resize the window), you'd 
have to re-call the function, which would redraw the figure a couple of times 
before drawing the final figure. That's all to say: this is a fairly slow 
function. If you don't have subplots (like in your example), you can call 
layout.tight_borders() (instead of layout.tight()), which only requires a 
single redraw.

When I originally posted this to the developers list, the functions didn't work 
with the GtkAgg backend. As far as I know, this hasn't changed. It should work 
fine for Qt4Agg, macosx, and TkAgg backends.


import numpy as np

import matplotlib.pyplot as plt
from matplotlib.transforms import TransformedBbox, Affine2D


PAD_INCHES = 0.1


def tight(pad_inches=PAD_INCHES, h_pad_inches=None, w_pad_inches=None):
Adjust subplot parameters to give specified padding.

Parameters
--
pad_inches : float
minimum padding between the figure edge and the edges of subplots.
h_pad_inches, w_pad_inches : float
minimum padding (height/width) between edges of adjacent subplots.
Defaults to `pad_inches`.

if h_pad_inches is None:
h_pad_inches = pad_inches
if w_pad_inches is None:
w_pad_inches = pad_inches
fig = plt.gcf()
tight_borders(fig, pad_inches=pad_inches)
# NOTE: border padding affects subplot spacing; tighten border first
tight_subplot_spacing(fig, h_pad_inches, w_pad_inches)


def tight_borders(fig, pad_inches=PAD_INCHES):
Stretch subplot boundaries to figure edges plus padding.
# call draw to update the renderer and get accurate bboxes.
fig.canvas.draw()
bbox_original = fig.bbox_inches
bbox_tight = _get_tightbbox(fig, pad_inches)

# figure dimensions ordered like bbox.extents: x0, y0, x1, y1
lengths = np.array([bbox_original.width, bbox_original.height,
bbox_original.width, bbox_original.height])
whitespace = (bbox_tight.extents - bbox_original.extents) / lengths

# border padding ordered like bbox.extents: x0, y0, x1, y1
current_borders = np.array([fig.subplotpars.left, fig.subplotpars.bottom,
fig.subplotpars.right, fig.subplotpars.top])

left, bottom, right, top = current_borders - whitespace
fig.subplots_adjust(bottom=bottom, top=top, left=left, right=right)


def _get_tightbbox(fig, pad_inches):
renderer = fig.canvas.get_renderer()
bbox_inches = fig.get_tightbbox(renderer)
return bbox_inches.padded(pad_inches)


def tight_subplot_spacing(fig, h_pad_inches, w_pad_inches):
Stretch subplots so adjacent subplots are separated by given padding.
# Zero hspace and wspace to make it easier to calculate the spacing.
fig.subplots_adjust(hspace=0, wspace=0)
fig.canvas.draw()

figbox = fig.bbox_inches
ax_bottom, ax_top, ax_left, ax_right = _get_grid_boundaries(fig)
nrows, ncols = ax_bottom.shape

subplots_height = fig.subplotpars.top - fig.subplotpars.bottom
if nrows  1:
h_overlap_inches = ax_top[1:] - ax_bottom[:-1]
hspace_inches = h_overlap_inches.max() + h_pad_inches
hspace_fig_frac = hspace_inches / figbox.height
hspace = _fig_frac_to_cell_frac(hspace_fig_frac, subplots_height, nrows)
fig.subplots_adjust(hspace=hspace)

subplots_width = fig.subplotpars.right - fig.subplotpars.left
if ncols  1:
w_overlap_inches = ax_right[:,:-1] - ax_left[:,1:]
wspace_inches = w_overlap_inches.max() + w_pad_inches
wspace_fig_frac = wspace_inches / figbox.width
wspace = _fig_frac_to_cell_frac(wspace_fig_frac, subplots_width, ncols)
fig.subplots_adjust(wspace=wspace)


def _get_grid_boundaries(fig):
Return grid boundaries for bboxes of subplots

Returns
---
ax_bottom, ax_top, ax_left, ax_right : array
bbox cell-boundaries of subplot grid. If 

Re: [Matplotlib-users] Z channel

2010-09-16 Thread Tony S Yu

On Sep 16, 2010, at 12:06 PM, Daπid wrote:

 No, it is not. The Z channel is an aditional number per pixel that
 haves the information of the deepness. When you render an image you
 can keep this information for adding mist, without rendering again,
 for example.
 
 I don't know if I have been able to explain myself, my mind is not
 really clear today. ;-)

Hi David,

I'm also having a difficult time understanding what you're after. Your 
description sounds to me like a normal image plot or pcolor plot; for example,

http://matplotlib.sourceforge.net/examples/pylab_examples/image_interp.html

http://matplotlib.sourceforge.net/examples/pylab_examples/pcolor_small.html

If what you're suggesting is different, then maybe you can link to a 
picture/plot of what you're after. (Or if you can't find anything, maybe you 
could draw an example of the plot).

Best,
-Tony


 
 On Thu, Sep 16, 2010 at 5:12 PM, Benjamin Root ben.r...@ou.edu wrote:
 On Thu, Sep 16, 2010 at 12:03 AM, Daπid davidmen...@gmail.com wrote:
 
 Does MPL support in any way the Z channel? If not, is there any
 possibility to use it? For example, to create a parallel matrix of the
 same dimensions of the image with the values of Z in each pixel.
 
 Thank you very much.
 
 David.
 
 
 David, I am not entirely certain I understand what you mean.  Perhaps you
 are speaking of Z-order?  Using the zorder kwarg in various plotting
 commands, I can manually control the order in which elements are rendered.
 When figures are saved, depending on the file format, this information can
 get flattened, and therefore lost, and other formats (most of the
 vector-based formats) maintain this information, I believe.
 
 Does that help?
 Ben Root
 
 
 
 --
 Start uncovering the many advantages of virtual appliances
 and start using them to simplify application deployment and
 accelerate your shift to cloud computing.
 http://p.sf.net/sfu/novell-sfdev2dev
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
Start uncovering the many advantages of virtual appliances
and start using them to simplify application deployment and
accelerate your shift to cloud computing.
http://p.sf.net/sfu/novell-sfdev2dev
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Line plot orientation

2010-09-11 Thread Tony S Yu

On Sep 11, 2010, at 12:00 PM, Radek Machulka wrote:

 Hi Folks,
 
 I am trying to do something similar to
 http://matplotlib.sourceforge.net/examples/pylab_examples/scatter_hist.html,
 but with a line plots instead of histograms.
 My problem is how to set orientation of line plot if there is no
 'orientation' argument (line axHisty.hist(y, bins=bins,
 orientation='horizontal') in the example).
 
 Thanks a lot
 Radek

Since a line plot doesn't really have an orientation, this might be a lot 
simpler than you think. If I understand your question, you can just switch your 
x and y data to get the desired behavior.

Continuing the example you link to, just remove the lines that create the 
histogram (last 4 lines before plt.show) and replace with normal plot commands; 
for example:

bins = np.arange(-lim, lim + binwidth, binwidth)
x_hist, _ = np.histogram(x, bins=bins)
y_hist, _ = np.histogram(y, bins=bins)
x_bin_centers = y_bin_centers = (bins[:-1] + bins[1:])/2.
axHistx.plot(x_bin_centers, x_hist)
axHisty.plot(y_hist, y_bin_centers)
plt.show()

The first line above marks the last line in the example script that you should 
keep. Note that you don't have to use histogram data (x_hist, y_hist); I only 
do so to simplify the example. Also, x_bin_centers and y_bin_centers are only 
equal because the scatter data is square.

Is this what you were going for?

-Tony


--
Start uncovering the many advantages of virtual appliances
and start using them to simplify application deployment and
accelerate your shift to cloud computing
http://p.sf.net/sfu/novell-sfdev2dev
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Adjusting Image size

2010-09-10 Thread Tony S Yu

On Sep 10, 2010, at 5:27 AM, Nils Wagner wrote:

 Hi all,
 
 what is needed to save a figure when the size is given in 
 pixels, i.e. 1024x772 ?
 The default is 800x600 pixels.
 
 from pylab import plot, savefig
 from numpy import sin,linspace,pi
 x = linspace(0,2*pi,200)
 plot(x,sin(x))
 savefig('test')
 
 Nils

You can try creating a figure with the correct aspect ratio and then setting a 
corresponding dpi when you save:

#---
import matplotlib.pyplot as plt
import numpy as np

plt.figure(figsize=(10.24, 7.72))
x = np.linspace(0,2*np.pi,200)
plt.plot(x, np.sin(x))
plt.savefig('test', dpi=100)
#---

I had mixed results with this: I would occasionally get figures that were one 
pixel smaller than desired.

Best,
-Tony
--
Automate Storage Tiering Simply
Optimize IT performance and efficiency through flexible, powerful, 
automated storage tiering capabilities. View this brief to learn how
you can reduce costs and improve performance. 
http://p.sf.net/sfu/dell-sfdev2dev
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Thicker Frame and Remove Part of Frame

2010-09-10 Thread Tony S Yu

On Sep 10, 2010, at 10:42 AM, Ted Kord wrote:

 Hi
 
 How can I:
 
 1. make the frame of the plot thicker and
 2. remove the top and right of the frame.
 
 Thanks
 
 Ted

There are probably a number of ways to do this (partly because spines are 
relatively new). Here's one possibility:

import matplotlib.pyplot as plt

f, ax = plt.subplots()
ax.plot([0, 1])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_linewidth(3)
ax.spines['left'].set_linewidth(3)
plt.show()

Best,
-Tony


--
Automate Storage Tiering Simply
Optimize IT performance and efficiency through flexible, powerful, 
automated storage tiering capabilities. View this brief to learn how
you can reduce costs and improve performance. 
http://p.sf.net/sfu/dell-sfdev2dev
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Triangle in a graph

2010-09-09 Thread Tony S Yu

On Sep 9, 2010, at 10:53 AM, Bernardo Rocha wrote:

 Hi everyone,
 
 I would like to know if it is possible (I guess it is) and how can I do a 
 plot such as the one in the attached figure?
 
 Could someone help me with this? I know that this one was done in gnuplot, 
 but I would like to use matplotlib.
 
 Thanks in advance.
 Bernardo M. R.

Hi Bernardo,

I have some functions which I use to draw slope markers (attached). There are 
examples of how to use it in the if-main block at the bottom of the file. It 
should be simple enough to use and works for linear and log scales.

The functions have grown sort of organically, so they're not as polished as 
they could be. In particular, the handling of linear/log scales could be 
refactored (probably by making slope marker a subclass of Polygon). Anyway, I 
haven't gotten around to cleaning things up, but the functions are very usable 
as is.

Hope that helps,
-Tony

import numpy as np
import matplotlib.pyplot as plt


def slope_marker(origin, slope, size_frac=0.1, pad_frac=0.1, ax=None,
 invert=False):
Plot triangular slope marker labeled with slope.

Parameters
--
origin : (x, y)
tuple of x, y coordinates for the slope
slope : float or (rise, run)
the length of the slope triangle
size_frac : float
the fraction of the xaxis length used to determine the size of the slope
marker. Should be less than 1.
pad_frac : float
the fraction of the slope marker used to pad text labels. Should be less 
than 1.
invert : bool
Normally, the slope marker is below a line for positive slopes and above
a line for negative slopes; `invert` flips the marker.

if ax is None:
ax = plt.gca()

if np.iterable(slope):
rise, run = slope
slope = float(rise) / run
else:
rise = run = None

x0, y0 = origin
xlim = ax.get_xlim()
dx_linear = size_frac * (xlim[1] - xlim[0])
dx_decades = size_frac * (np.log10(xlim[1]) - np.log10(xlim[0]))

if invert:
dx_linear = -dx_linear
dx_decades = -dx_decades

if ax.get_xscale() == 'log':
log_size = dx_decades
dx = _log_distance(x0, log_size)
x_run = _text_position(x0, log_size/2., scale='log')
x_rise = _text_position(x0+dx, dx_decades*pad_frac, scale='log')
else:
dx = dx_linear
x_run = _text_position(x0, dx/2.)
x_rise = _text_position(x0+dx, pad_frac * dx)

if ax.get_yscale() == 'log':
log_size = dx_decades * slope
dy = _log_distance(y0, log_size)
y_run = _text_position(y0, -dx_decades*slope*pad_frac, scale='log')
y_rise = _text_position(y0, log_size/2., scale='log')
else:
dy = dx_linear * slope
y_run = _text_position(y0, -(pad_frac * dy))
y_rise = _text_position(y0, dy/2.)

x_pad = pad_frac * dx
y_pad = pad_frac * dy

va = 'top' if y_pad  0 else 'bottom'
ha = 'left' if x_pad  0 else 'right'
if rise is not None:
ax.text(x_run, y_run, str(run), va=va, ha='center')
ax.text(x_rise, y_rise, str(rise), ha=ha, va='center')
else:
ax.text(x_rise, y_rise, str(slope), ha=ha, va='center')

ax.add_patch(_slope_triangle(origin, dx, dy))


def log_displace(x0, dx_log=None, x1=None, frac=None):
Return point displaced by a logarithmic value.

For example, if you want to move 1 decade away from `x0`, set `dx_log` = 1,
such that for `x0` = 10, we have `displace(10, 1)` = 100

Parameters
--
x0 : float
reference point
dx_log : float
displacement in decades.
x1 : float
end point
frac : float
fraction of line (on logarithmic scale) between x0 and x1

if dx_log is not None:
return 10**(np.log10(x0) + dx_log)
elif x1 is not None and frac is not None:
return 10**(np.log10(x0) + frac * np.log10(float(x1)/x0))
else:
raise ValueError('Specify `dx_log` or both `x1` and `frac`.')


def _log_distance(x0, dx_decades):
return log_displace(x0, dx_decades) - x0

def _text_position(x0, dx, scale='linear'):
if scale == 'linear':
return x0 + dx
elif scale == 'log':
return log_displace(x0, dx)
else:
raise ValueError('Unknown value for `scale`: %s' % scale)


def _slope_triangle(origin, dx, dy, ec='none', fc='0.8', **poly_kwargs):
Return Polygon representing slope.
  /|
 / | dy
/__|
 dx

verts = [np.asarray(origin)]
verts.append(verts[0] + (dx, 0))
verts.append(verts[0] + (dx, dy))
return plt.Polygon(verts, ec=ec, fc=fc, **poly_kwargs)


if __name__ == '__main__':
plt.plot([0, 2], [0, 1])
slope_marker((1, 0.4), (1, 2))

x = np.logspace(0, 2)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

ax1.loglog(x, x**0.5)
slope_marker((10, 2), 

Re: [Matplotlib-users] Math fonts not working after upgrading to MPL 1.0

2010-09-08 Thread Tony S Yu

On Sep 8, 2010, at 11:56 AM, Jeremy Conlin wrote:

 I have trouble getting any symbols or any super/sub scripts to work
 since I upgraded to 1.0 a few months ago.  I always get a message
 saying that some font isn't found.  This occurs whenever I try to put
 symbols, superscripts, or subscripts in a label, or when I use a log
 scale (because then it MPL has to use superscripts).  I have tried
 changing my matplotlibrc file but haven't found any combination of
 settings that help.
 
 To illustrate the problem, I have included three files, one python
 file and the other the error as captured from the output as well as my
 matplotlibrc file.  The python file is trivial:
 
 # -
 import matplotlib.pyplot as pyplot
 
 pyplot.plot([1,2,3], label='$\alpha  \beta$')
 
 pyplot.legend()
 pyplot.show()
 # -
 
 Can someone please help me figure out what is wrong?  I'm on a Mac
 running 10.6, python 2.6, matplotlib 1.0, and I have TeX installed.
 
Works on my system if you use a raw string (note ``r`` before string):

 pyplot.plot([1,2,3], label=r'$\alpha  \beta$')

Does that fix your problem?

-Tony

--
This SF.net Dev2Dev email is sponsored by:

Show off your parallel programming skills.
Enter the Intel(R) Threading Challenge 2010.
http://p.sf.net/sfu/intel-thread-sfd
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Math fonts not working after upgrading to MPL 1.0

2010-09-08 Thread Tony S Yu

On Sep 8, 2010, at 2:10 PM, Jeremy Conlin wrote:

 On Wed, Sep 8, 2010 at 10:42 AM, Tony S Yu tsy...@gmail.com wrote:
 
 On Sep 8, 2010, at 11:56 AM, Jeremy Conlin wrote:
 
 I have trouble getting any symbols or any super/sub scripts to work
 since I upgraded to 1.0 a few months ago.  I always get a message
 saying that some font isn't found.  This occurs whenever I try to put
 symbols, superscripts, or subscripts in a label, or when I use a log
 scale (because then it MPL has to use superscripts).  I have tried
 changing my matplotlibrc file but haven't found any combination of
 settings that help.
 
 To illustrate the problem, I have included three files, one python
 file and the other the error as captured from the output as well as my
 matplotlibrc file.  The python file is trivial:
 
 # -
 import matplotlib.pyplot as pyplot
 
 pyplot.plot([1,2,3], label='$\alpha  \beta$')
 
 pyplot.legend()
 pyplot.show()
 # -
 
 Can someone please help me figure out what is wrong?  I'm on a Mac
 running 10.6, python 2.6, matplotlib 1.0, and I have TeX installed.
 
 Works on my system if you use a raw string (note ``r`` before string):
 
 pyplot.plot([1,2,3], label=r'$\alpha  \beta$')
 
 Does that fix your problem?
 
 Unfortunately, no.  When I use a raw string, I just get *a@ instead
 of the expected result.  See attached figure for proof.  I still get a
 long list of errors of fonts not being found.
 
 Jeremy
 mathfont.pdf


Hmm, that strange. All the fonts it says aren't found are fonts that should be 
included in the Matplotlib install. I have pretty much the same setup as you 
(OSX 10.6, python 2.6), although I'm on Matplotlib trunk. Is it possible your 
install got screwed up some how. Have you tried a clean install of Matplotlib?

If that doesn't work, I'm afraid I won't be of much help, since I can't really 
reproduce this on my system. Maybe, someone who knows the font system better 
can help.

Best,
-Tony






--
This SF.net Dev2Dev email is sponsored by:

Show off your parallel programming skills.
Enter the Intel(R) Threading Challenge 2010.
http://p.sf.net/sfu/intel-thread-sfd
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] bug? line misses points with negative coordinates

2010-09-03 Thread Tony S Yu

On Sep 3, 2010, at 4:33 AM, Sébastien Barthélemy wrote:

 Hello,
 
 While using sage [1], I got problems drawing a line: for some reason,
 the points with negative coordinates are not plotted (or are plotted
 on top of others due to an offset problem and thus I cannot see them).
 I can only reproduce the bug with specific data sets.
 
 I think I could track down the bug to matplotlib, which sage uses to
 render 2d plots.
 
 I included a sage script which generates the data set (in a pickle
 file), and a python script which draws the faulty line.
 
 Usage is :
 
 $ sage generate_data.sage
 $ python test_mpl.py
 
 I also included the pickled data, thus you don't need sage at all.
 I use matplotlib 1.0.0 for python 2.6 on mac os (as provided by macport).
 
 Could somebody here confirm the problem, and give me a hint about what
 is going on?

I can confirm the issue. This appears to be a drawing bug: when I pan the 
drawing so that the negative data touches the edge of the axes frame, the rest 
of the line is drawn. So the line object is being created, but for some reason 
it's not being drawn correctly.

The bug is really finicky: if I plot starting from the 3rd value of your data 
(i.e. slice xdata, ydata with [2:]), the line is drawn completely. The strange 
thing is that the first 100 or so data points defines the exact same point, so 
there's noting special about those first two points. (but this overlaying of 
data may be related to the bug)

I've reproduced the issue on TkAgg, Qt4Agg, and MacOSX backends, so maybe the 
bug is in backend_bases. (Note: unlike Agg backends, MacOSX backend doesn't 
show line even after panning the plot)

I don't really know how to debug drawing errors like this; so this is as far as 
can get.

Best,
-Tony

 
 Regards
 Sebastien
 
 [1] www.sagemath.org
 generate_data.sagetest_mpl.pytraj_mod.pickle

--
This SF.net Dev2Dev email is sponsored by:

Show off your parallel programming skills.
Enter the Intel(R) Threading Challenge 2010.
http://p.sf.net/sfu/intel-thread-sfd
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] bug? line misses points with negative coordinates

2010-09-03 Thread Tony S Yu

On Sep 3, 2010, at 10:23 AM, Sébastien Barthélemy wrote:

 CC to matplotlib-devel  matplotlib-users
 
 2010/9/3 Tony S Yu tsy...@gmail.com:
 On Sep 3, 2010, at 4:33 AM, Sébastien Barthélemy wrote:
 
 Hello,
 
 While using sage [1], I got problems drawing a line: for some reason,
 the points with negative coordinates are not plotted (or are plotted
 on top of others due to an offset problem and thus I cannot see them).
 I can only reproduce the bug with specific data sets.
 
 [1] www.sagemath.org
 
 I think I could track down the bug to matplotlib, which sage uses to
 render 2d plots.
 
 I included a sage script which generates the data set (in a pickle
 file), and a python script which draws the faulty line.
 
 Usage is :
 
 $ sage generate_data.sage
 $ python test_mpl.py
 
 I also included the pickled data, thus you don't need sage at all.
 I use matplotlib 1.0.0 for python 2.6 on mac os (as provided by macport).
 
 Could somebody here confirm the problem, and give me a hint about what
 is going on?
 
 I can confirm the issue.
 
 Great, thank you. I filed a bug:
 https://sourceforge.net/tracker/?func=detailaid=3058804group_id=80706atid=560720
 
 This appears to be a drawing bug: when I pan the drawing so that the 
 negative data touches the edge of the axes frame, the rest of the line is 
 drawn. So the line object is being created, but for some reason it's not 
 being drawn correctly.
 
 The bug is really finicky: if I plot starting from the 3rd value of your 
 data (i.e. slice xdata, ydata with [2:]), the line is drawn completely. The 
 strange thing is that the first 100 or so data points defines the exact same 
 point, so there's noting special about those first two points. (but this 
 overlaying of data may be related to the bug)
 
 I've reproduced the issue on TkAgg, Qt4Agg, and MacOSX backends, so maybe 
 the bug is in backend_bases. (Note: unlike Agg backends, MacOSX backend 
 doesn't show line even after panning the plot)
 
 I don't really know how to debug drawing errors like this; so this is as far 
 as can get.

I'm not sure if I should respond to this email or the bug report, but since I 
made the claim here, I'll correct myself here: The bug is not in the drawing 
code as I had suggested. 

The bug is related to path simplification. If you turn off path simplification 
(e.g. plt.rc('path', simplify=False), the line is drawn in its entirety. This 
also explains why the bug disappeared when I trimmed the first two points: path 
simplification is triggered from data sets with atleast 128 points (your data 
has 129, so trimming two points turned off path simplification).

I just wanted to correct my earlier comments.

-T



--
This SF.net Dev2Dev email is sponsored by:

Show off your parallel programming skills.
Enter the Intel(R) Threading Challenge 2010.
http://p.sf.net/sfu/intel-thread-sfd
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Change default font

2010-09-01 Thread Tony S Yu

On Sep 1, 2010, at 5:10 PM, Ali Fessi wrote:

  Hi,
 
 is there a way to change the default font, e.g., to Times New Roman?! 
 I've been looking at the rcparams but it's kind of confusing.
 
 Cheers.


Yes, but first you should make sure the font is on your system and is of the 
correct type, i.e. TrueType (TTF). AND you have to make sure know the name of 
it (some fonts may have names that aren't obvious). To check the name, type the 
following in the python interpreter:

 from matplotlib import font_manager
 font_manager.findfont('Times New Roman')

If the font manager finds it, then it should return the path to a ttf file with 
a similar name; otherwise, it'll return some default font (on my system 
Vera.ttf).

Assuming you've got all that sorted out, you can set the default font in each 
script, or in your matplotlibrc file (i.e. globally). But first note that Times 
New Roman is a serif font; matplotlib uses sans-serif fonts by default (at 
least on my system). So if you decide to go with Times New Roman, or another 
serif font, you need to change the font family, as well. Here's some examples

1) In a script, add:

import matplotlib.pyplot as plt
plt.rc('font', family='serif')
plt.rc('font', serif='Times New Roman')


2) In your matplotlibrc file, add:

font.family: serif
font.serif: Times New Roman

Best,
-Tony
--
This SF.net Dev2Dev email is sponsored by:

Show off your parallel programming skills.
Enter the Intel(R) Threading Challenge 2010.
http://p.sf.net/sfu/intel-thread-sfd
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] MPL = Location of new figure on desktop

2010-08-20 Thread Tony S Yu

On Aug 20, 2010, at 10:41 AM, Benjamin Root wrote:

 On Fri, Aug 20, 2010 at 2:18 AM, Eric Emsellem eemse...@eso.org wrote:
 Hi
 
 I have one very nagging issue which I would like to solve with matplotlib once
 and for all: this may have to do with my desktop windown manager but I 
 couldn't
 find much there, so any input is welcome.
 
 When I open a new figure, the figure ALWAYS comes BELOW my current xterm 
 (using
 KDE 4.3) and ALWAYS in the wrong place (top left corner where I usually put
 other windows). I would like some smart location for that figure so I don't
 have systematically to get it up and move it when I open a new figure. Is this
 linked to matplotlib? (this is the only application which is not managed
 properly in this context). I am using ipython -pylab as a working context (on
 opensuse 11.2).
 
 thanks and cheers
 
 Eric
 
 
 Eric,
 
 One possibility for this behavior might be that you might be defaulting to a 
 different backend than QT.  I would imagine if matplotlib is defaulting to 
 the GTKAgg backend or the Tk backend, then the figure window would not behave 
 properly in the window manager.  You can set a default backend value to 
 Qt4Agg in your matplotlibrc file.  Maybe that would work.
 
 Ben Root

I've had the same issue as Eric using Qt4Agg as the backend (and with all other 
backends I've used). As Eric mentioned, I have this windowing issue with 
ipython -pylab, but this issue also arises when running scripts from the 
command line and from my text editor (i.e. it's not ipython specific).

-Tony


--
This SF.net email is sponsored by 

Make an app they can't live without
Enter the BlackBerry Developer Challenge
http://p.sf.net/sfu/RIM-dev2dev ___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] MPL = Location of new figure on desktop

2010-08-20 Thread Tony S Yu

On Aug 20, 2010, at 10:59 AM, Benjamin Root wrote:

 
 
 On Fri, Aug 20, 2010 at 9:51 AM, Tony S Yu tsy...@gmail.com wrote:
 
 On Aug 20, 2010, at 10:41 AM, Benjamin Root wrote:
 
 On Fri, Aug 20, 2010 at 2:18 AM, Eric Emsellem eemse...@eso.org wrote:
 Hi
 
 I have one very nagging issue which I would like to solve with matplotlib 
 once
 and for all: this may have to do with my desktop windown manager but I 
 couldn't
 find much there, so any input is welcome.
 
 When I open a new figure, the figure ALWAYS comes BELOW my current xterm 
 (using
 KDE 4.3) and ALWAYS in the wrong place (top left corner where I usually put
 other windows). I would like some smart location for that figure so I don't
 have systematically to get it up and move it when I open a new figure. Is 
 this
 linked to matplotlib? (this is the only application which is not managed
 properly in this context). I am using ipython -pylab as a working context (on
 opensuse 11.2).
 
 thanks and cheers
 
 Eric
 
 
 Eric,
 
 One possibility for this behavior might be that you might be defaulting to a 
 different backend than QT.  I would imagine if matplotlib is defaulting to 
 the GTKAgg backend or the Tk backend, then the figure window would not 
 behave properly in the window manager.  You can set a default backend value 
 to Qt4Agg in your matplotlibrc file.  Maybe that would work.
 
 Ben Root
 
 I've had the same issue as Eric using Qt4Agg as the backend (and with all 
 other backends I've used). As Eric mentioned, I have this windowing issue 
 with ipython -pylab, but this issue also arises when running scripts from the 
 command line and from my text editor (i.e. it's not ipython specific).
 
 -Tony
 
 
 
 Does it also happen with the QtAgg backend?  Does the behavior change based 
 on which backend you choose?  That might help narrow down whether it is a 
 problem with particular backends or with the backend interface.
 
 Ben Root

A couple of corrections: 

1) I wasn't clear earlier: I was agreeing with Eric on the fact that the plot 
window appeared below other windows. The location (e.g. top-left corner)  
depends on the backend I use.

2) I was wrong that all backends show up below the terminal window: the MacOSX 
backend creates plots above other windows (unfortunately, I can't test QtAgg; 
only macosx, qt4agg, and tkagg).

-Tony

--
This SF.net email is sponsored by 

Make an app they can't live without
Enter the BlackBerry Developer Challenge
http://p.sf.net/sfu/RIM-dev2dev ___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] creating figures of exact size

2010-08-17 Thread Tony S Yu

On Aug 17, 2010, at 11:02 AM, Bala subramanian wrote:

 Friends,
 
 I am trying to make a figure for publication. I am making a double column 
 figure of 7inch as per journal guidelines. The figure comes out nicely but 
 the final size of the figure that is saved is not what i have given in 
 'figsize'. It is 10inch X 5.38 inch. How can i make mpl to create the figure 
 of exact size and resolution?
 
 fig=plt.figure(figsize=(7,4))
 fig.subplots_adjust(wspace=0.1,hspace=0.1)
 ax1=fig.add_subplot(221)
 ax2=fig.add_subplot(222,sharex=ax1,sharey=ax1)
 ax3=fig.add_subplot(223,sharex=ax1,sharey=ax1)
 ax4=fig.add_subplot(224,sharex=ax1,sharey=ax1)
 
 Thanks,
 Bala

That's strange. I don't see any problems with the figure size on my system. 
This may seem like a silly question, but do you have the same sizing issue for 
the following code:

import matplotlib.pyplot as plt
fig=plt.figure(figsize=(7,4))
fig.subplots_adjust(wspace=0.1,hspace=0.1)
ax1=fig.add_subplot(221)
ax2=fig.add_subplot(222,sharex=ax1,sharey=ax1)
ax3=fig.add_subplot(223,sharex=ax1,sharey=ax1)
ax4=fig.add_subplot(224,sharex=ax1,sharey=ax1)
plt.savefig('test.pdf')
# works fine on my system with png, pdf, and eps

I just want to make sure you aren't altering the figure in any other way before 
you save.

Are you using savefig or are you saving from a GUI window? Are you on a current 
version of matplotlib (if yes, you might be interested in `plt.subplots` to 
create your axes)? What image format are you using?

-Tony



--
This SF.net email is sponsored by 

Make an app they can't live without
Enter the BlackBerry Developer Challenge
http://p.sf.net/sfu/RIM-dev2dev 
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Hints on sizing plot elements?

2010-08-12 Thread Tony S Yu

On Aug 12, 2010, at 1:08 AM, Russell E. Owen wrote:

 I'm making a strip chart widget (which I plan to make publicly available 
 when finished). The basics are working fine, but the automatic sizing is 
 not doing so well. Strip charts are typically short, and when suitably 
 short the X axis annotations are partially truncated.
 
 So...can I convince the automatic sizer to always show the full X (time) 
 axis annotations and put all the variable sizing into the data area? Or 
 do I have to manually set them somehow?

As far as I know, there's nothing to automatically resize the padding around 
the the axes. (The manual way to do it is to call `fig.subplots_adjust`). I 
wrote a helper script (attached below) to adjust the layout so that there's a 
specified amount of padding around the axes.

Unfortunately, this resizer doesn't function correctly when using the GTK 
backend. It apparently works fine with TkAgg, MacOSX, and Qt4Agg backends.


 Also, is there a way from my software (not a .matplotlibrc file) to 
 globally make the default background color white for axis annotation 
 areas? Right now the background is gray for annotations and while for 
 plot area and I'd prefer it was all white.
 
 -- Russell


Just set plt.rc('figure', facecolor='w') in your code (assuming you've imported 
matplotlib.pyplot as plt).

Best,
-Tony


import numpy as np

import matplotlib.pyplot as plt
from matplotlib.transforms import TransformedBbox, Affine2D


PAD_INCHES = 0.1


def tight_layout(pad_inches=PAD_INCHES, h_pad_inches=None, w_pad_inches=None):
Adjust subplot parameters to give specified padding.

Parameters
--
pad_inches : float
minimum padding between the figure edge and the edges of subplots.
h_pad_inches, w_pad_inches : float
minimum padding (height/width) between edges of adjacent subplots.
Defaults to `pad_inches`.

if h_pad_inches is None:
h_pad_inches = pad_inches
if w_pad_inches is None:
w_pad_inches = pad_inches
fig = plt.gcf()
tight_borders(fig, pad_inches=pad_inches)
# NOTE: border padding affects subplot spacing; tighten border first
tight_subplot_spacing(fig, h_pad_inches, w_pad_inches)


def tight_borders(fig, pad_inches=PAD_INCHES):
Stretch subplot boundaries to figure edges plus padding.
# call draw to update the renderer and get accurate bboxes.
fig.canvas.draw()
bbox_original = fig.bbox_inches
bbox_tight = _get_tightbbox(fig, pad_inches)

# figure dimensions ordered like bbox.extents: x0, y0, x1, y1
lengths = np.array([bbox_original.width, bbox_original.height,
bbox_original.width, bbox_original.height])
whitespace = (bbox_tight.extents - bbox_original.extents) / lengths

# border padding ordered like bbox.extents: x0, y0, x1, y1
current_borders = np.array([fig.subplotpars.left, fig.subplotpars.bottom,
fig.subplotpars.right, fig.subplotpars.top])

left, bottom, right, top = current_borders - whitespace
fig.subplots_adjust(bottom=bottom, top=top, left=left, right=right)


def _get_tightbbox(fig, pad_inches):
renderer = fig.canvas.get_renderer()
bbox_inches = fig.get_tightbbox(renderer)
return bbox_inches.padded(pad_inches)


def tight_subplot_spacing(fig, h_pad_inches, w_pad_inches):
Stretch subplots so adjacent subplots are separated by given padding.
# Zero hspace and wspace to make it easier to calculate the spacing.
fig.subplots_adjust(hspace=0, wspace=0)
fig.canvas.draw()

figbox = fig.bbox_inches
ax_bottom, ax_top, ax_left, ax_right = _get_grid_boundaries(fig)
nrows, ncols = ax_bottom.shape

subplots_height = fig.subplotpars.top - fig.subplotpars.bottom
if nrows  1:
h_overlap_inches = ax_top[1:] - ax_bottom[:-1]
hspace_inches = h_overlap_inches.max() + h_pad_inches
hspace_fig_frac = hspace_inches / figbox.height
hspace = _fig_frac_to_cell_frac(hspace_fig_frac, subplots_height, nrows)
fig.subplots_adjust(hspace=hspace)

subplots_width = fig.subplotpars.right - fig.subplotpars.left
if ncols  1:
w_overlap_inches = ax_right[:,:-1] - ax_left[:,1:]
wspace_inches = w_overlap_inches.max() + w_pad_inches
wspace_fig_frac = wspace_inches / figbox.width
wspace = _fig_frac_to_cell_frac(wspace_fig_frac, subplots_width, ncols)
fig.subplots_adjust(wspace=wspace)


def _get_grid_boundaries(fig):
Return grid boundaries for bboxes of subplots

Returns
---
ax_bottom, ax_top, ax_left, ax_right : array
bbox cell-boundaries of subplot grid. If a subplot spans cells, the grid
boundaries cutting through that subplot will be masked.

nrows, ncols, n = fig.axes[0].get_geometry()
# Initialize boundaries as masked arrays; in the future, support subplots 
# that span multiple rows/columns, which would 

Re: [Matplotlib-users] Sequential Calls to create bar charts jumbles output on second. first always ok.

2010-08-11 Thread Tony S Yu

On Aug 11, 2010, at 6:56 AM, Rob Schneider wrote:

 
 I extract data out of a database (via Django and Python).  I'm drawing two 
 bar charts.  One is a stacked bar, and one is a simple bar.
 The code for each graph is in their own function.  I call the function to 
 draw the graph sequencially (in function CreateAllWebSite() below).
 
 Problem is that when I do this, the graph called second comes out all 
 jumbled.  See attached copies of png files.  If I swap the function calls, 
 always first is ok and the the second one is jumbled.  If I call them one at 
 a time, they both work just fine (which is how i developed the second).  once 
 put together, the second is wrong.  For example, the legend from the first 
 graph gets put on the second graph . The x-axis for the second is all jumbled 
 at the bottom left corner of the graph instead of along the x-axis properly.  
 
 I'm using Matplotlib 0.98.5.3 on OS X.  I will upgrade to 1.0 of Matplot lib 
 soon.
 
 I suspect some sort of memory issue; perhaps caused by how I import 
 matplotlib in the global section of the python program; but far as I can tell 
 this is correct, or is it?  I suspect memory as how else would legend from 
 the first graph get put on the second graph? Is there some sort of reset 
 function to call to clear out the old graph? I sort of thought that calling a 
 completely different function would cover that.
 
 Here's the code extract with portions I think no relevant snipped out. From 
 debugging I'm confident the number arrays holding the data is ok.  As I said, 
 when producing the graphs one at a time, it work fine.  So that code snipped 
 out below.
 
 #!/usr/bin/env python
 # −*− coding: UTF−8 −*−
 
 import matplotlib
 matplotlib.use('Agg') # before importing pyplot per docs
 import matplotlib.pyplot as plt
 import numpy as np
 
 [snipped the import of Python and Django libraries]
 
 ###
 def CreateAllWebSite():
  # here is the one function that calls the two graphing functions 
 sequentially.
  # whichever of these is called first is done fine.  Second flawed.  calling 
 one at at time, each works ok
  CreateMemberStatFigure()
  CreateMemberStatCategoryFigure()
 ###
 def CreateMemberStatFigure():
 # this function creates a stacked bar chart
 [snipped out portions where arrays created]

Hi Rob,

It would be helpful if you could provide a runnable example. I know it's a 
pain, but you should simplify your example so that it's runnable with only 
matplotlib and numpy You should create some fake data to replace these portions 
that you've cut out. Plus there are some (Django?) classes/functions/globals 
that are undefined.

Best,
-Tony




--
This SF.net email is sponsored by 

Make an app they can't live without
Enter the BlackBerry Developer Challenge
http://p.sf.net/sfu/RIM-dev2dev 
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] PolyCollection API

2010-07-27 Thread Tony S Yu

On Jul 27, 2010, at 2:14 PM, Mathew Yeates wrote:

 I installed matplotlib 1.0 and now I get a different error
 s=[0,0,8,8]
 ys=[0,8,8,0]
 verts=zip(xs,ys)
 poly = PolyCollection(verts)
 
 fails at line 587 in collections because
 xy = array([0, 0]) # xy.shape = (2,)
 and line 587 says xy = np.concatenate([xy, np.zeros((1,2))])
 
 What do I do?
 
 -Mathew
 


I don't really use PolyCollection, but the docstring suggests you need to put 
your verts inside of a list:
 *verts* is a sequence of ( *verts0*, *verts1*, ...) where
 *verts_i* is a sequence of *xy* tuples of vertices, or an
 equivalent :mod:`numpy` array of shape (*nv*, 2).
It's a bit confusing, but the first argument, verts, is actually a sequence, 
of a sequence, of vertices (the repetition is intentional). For example:

square = [(0, 0), (0, 4), (4, 4), (4, 0)]
triangle = [(0, 4), (0, 7), (4, 4)]
verts = [square, triangle]

In other words, the verts you created in your description describes a single 
polygon, where as verts should be a list of polygons.

-Tony
--
The Palm PDK Hot Apps Program offers developers who use the
Plug-In Development Kit to bring their C/C++ apps to Palm for a share 
of $1 Million in cash or HP Products. Visit us here for more details:
http://ad.doubleclick.net/clk;226879339;13503038;l?
http://clk.atdmt.com/CRS/go/247765532/direct/01/
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Case stories of software including Matplotlib

2010-07-27 Thread Tony S Yu

On Jul 27, 2010, at 1:31 PM, ms wrote:

 On 27/07/10 15:05, Benjamin Root wrote:
 On Tue, Jul 27, 2010 at 6:01 AM, German Ocampogeroca...@gmail.com  wrote:
 
 Good morning
 
 Do you know where I could get examples of case stories about
 commercial or open source software that has been developed using the
 Matplotlib library?
 
 Many Thanks
 
 German
 
 
 German,
 
 Interesting idea.  Might be something nice to add to the project page,
 maybe?
 
 I have no ready case story about it, but I developed and published a 
 MPL-based open source software here:
 
 http://code.google.com/p/hooke
 
 which has been presented in a peer-reviewed academic publication on 
 Bioinformatics ( 
 http://bioinformatics.oxfordjournals.org/cgi/content/abstract/btp180?ijkey=B9QGeobopuepKnZkeytype=ref
  
 )
 
 If you need information to build a case story, ask me -perhaps I can 
 help you if it's not too much work.
 
 cheers,
 M.


German, 

You might be interested in CellProfiler Analyst (http://www.cellprofiler.org/). 
Also, matplotlib is an optional dependency for FiPy 
(http://www.ctcms.nist.gov/fipy/).

Best,
-Tony--
The Palm PDK Hot Apps Program offers developers who use the
Plug-In Development Kit to bring their C/C++ apps to Palm for a share 
of $1 Million in cash or HP Products. Visit us here for more details:
http://ad.doubleclick.net/clk;226879339;13503038;l?
http://clk.atdmt.com/CRS/go/247765532/direct/01/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] sizing shapes on a plot to match axis units, not graphic points

2010-06-07 Thread Tony S Yu
On Jun 7, 2010, at 11:16 AM, Ian Stokes-Rees wrote:I'm generating a plot of NxN squares, where the size of the squarecorresponds to the correlation between the (i,j) point. Every (i,i)point equals 1.0. I'm using "scatter" to do this, but the sizingappears to be in "points" from the graphic, rather than "units" of thetwo axes. Is there some way to account for this, or is there somebetter way to generate this image?# result = n x n matrix of correlations between points (i,j)a = arange(n).repeat(n).reshape(n,n)b = a.transpose()scatter(a.flatten(), b.flatten(), s=result, marker='s')You can see an example here, where N=300: (note, this is a 2.5 MB image):http://abitibi.sbgrid.org/se/data/shared/biodb/scop-class/a/39/1/5/.meta/tmscore2.pngThanks,IanWhat you're doing sounds very similar to a Hinton diagrom (or at least the resulting image looks similar). There's an example of plotting such a diagram in the scipy cookbook:http://www.scipy.org/Cookbook/Matplotlib/HintonDiagramsThe implementation is pretty slow because it loops through the data and draws each square one by one. I wrote a faster alternative a while back (see attached). It uses a custom PolyCollection, which uses data units for the areas instead of figure units. Also, I just noticed there's another implementation of Hinton diagrams in the matplotlib examples folder (examples/api/hinton_demo.py). For some reason, this example doesn't appear on the website, otherwise I'd link to it.I believe the difference between your plot and a hinton diagram is that you have a different metric for calculating the size of the squares.-Tonyimport numpy as np
import matplotlib.pyplot as plt
import matplotlib.collections as collections
import matplotlib.transforms as transforms


class SquareCollection(collections.RegularPolyCollection):
Return a collection of squares.

def __init__(self, **kwargs):
super(SquareCollection, self).__init__(4, rotation=np.pi/4., **kwargs)

def get_transform(self):
Return transform scaling circle areas to data space.
ax = self.axes
pts2pixels = 72.0 / ax.figure.dpi
scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width
scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height
return transforms.Affine2D().scale(scale_x, scale_y)

def hinton(inarray, max_weight=None):
Draw Hinton diagram for visualizing a weight matrix.
ax = plt.gca()
ax.set_axis_bgcolor('gray')
# make sure we're working with a numpy array, not a numpy matrix
inarray = np.asarray(inarray)
height, width = inarray.shape
if max_weight is None:
max_weight = 2**np.ceil(np.log(np.max(np.abs(inarray)))/np.log(2))
weights = np.clip(inarray/max_weight, -1, 1)
rows, cols = np.mgrid[:height, :width]

pos = np.where(weights  0)
neg = np.where(weights  0)
for idx, color in zip([pos, neg], ['white', 'black']):
if len(idx[0])  0:
xy = zip(cols[idx], rows[idx])
circle_areas = np.pi / 2 * np.abs(weights[idx])
squares = SquareCollection(sizes=circle_areas, 
   offsets=xy, transOffset=ax.transData,
   facecolor=color, edgecolor=color)
ax.add_collection(squares, autolim=True)
plt.axis('scaled')
ax.set_xlim(-0.5, width-0.5)
ax.set_ylim(height-0.5, -0.5)
ax.set_xlabel('column')
ax.set_ylabel('row')
ax.xaxis.set_ticks_position('top')
ax.xaxis.set_label_position('top')


if __name__ == '__main__':
u = lambda x: 3/4. * x**2 - 0.5 * x
A = np.array([[0, 0.5, 1], [-0.5, 0, 0.5], [-1, -0.5, 0]])
print A
hinton(A)
plt.show()
--
ThinkGeek and WIRED's GeekDad team up for the Ultimate 
GeekDad Father's Day Giveaway. ONE MASSIVE PRIZE to the 
lucky parental unit.  See the prize list and enter to win: 
http://p.sf.net/sfu/thinkgeek-promo___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] MPL uses character not defined by cmr10?

2010-04-29 Thread Tony S Yu
There was a recentthread about the font sizesnot matching up between regular text and math text. I decided I'd try to get matching font sizes by using computer modern as the default font, so I added the following to my matplotlibrc file:font.family: seriffont.serif: cmr10This fixes the font size issue, but for some reason, MPL's minus sign seems to be using a character not defined by the computer modern fonts (see y-axis in attached image).Is there a fix for this missing character?Best,-TonyP.S. I'm using the cmr10 fonts provided by MPL (confirmed by using the findfont function).--
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] MPL uses character not defined by cmr10?

2010-04-29 Thread Tony S Yu

On Apr 29, 2010, at 10:43 PM, Tony S Yu wrote:

 
 On Apr 29, 2010, at 6:09 PM, Michael Droettboom wrote:
 
 Those Computer Modern fonts (specifically the Bakoma distribution of them 
 that matplotlib includes) use a custom character set mapping where many of 
 the characters are in completely arbitrary locations.  For regular text, 
 matplotlib expects a regular Unicode font (particularly to get the minus 
 sign).  Since cmr10 doesn't have a standard encoding, it just won't work.  
 
 
 Hey Mike,
 
 Thanks for your reply. That makes sense.
 
 An alternative work around (I presume) would be to install the computer 
 modern unicode fonts (I made sure to install the ttf version). However, I'm 
 having trouble getting MPL to find the fonts.
 
 The installed font is listed when calling 
 `mpl.font_manager.OSXInstalledFonts()`, but it's not found when calling 
 `mpl.font_manager.findfont` (with various names that would make sense: 
 cmunrm, CMU Serif, etc.)
 
 Any ideas on what I'm doing wrong?

Sorry, I meant to reply to the list.

After clearing the fontlist cache, I was able to get this fix working.

Just to summarize:

* download unicode version of computer modern fonts 
(http://sourceforge.net/projects/cm-unicode/files/)---make sure to get the ttf 
version

* clear out the fontlist cache (rm ~/.matplotlib/fontList.cache)

* add the following to ~/matplotlib/matplotlibrc:

font.family: serif
font.serif: CMU Serif

* alternatively, you could leave the default as sans serif and use the computer 
modern sans serif (unicode version):

font.sans-serif: CMU Sans Serif

These changes produce plots where the size of normal text matches that of 
mathtext.

Thanks for you help, Mike!

-Tony

--
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] MPL uses character not defined by cmr10?

2010-04-29 Thread Tony S Yu

On Apr 29, 2010, at 11:51 PM, Tony S Yu wrote:

 
 On Apr 29, 2010, at 10:43 PM, Tony S Yu wrote:
 
 
 On Apr 29, 2010, at 6:09 PM, Michael Droettboom wrote:
 
 Those Computer Modern fonts (specifically the Bakoma distribution of them 
 that matplotlib includes) use a custom character set mapping where many of 
 the characters are in completely arbitrary locations.  For regular text, 
 matplotlib expects a regular Unicode font (particularly to get the minus 
 sign).  Since cmr10 doesn't have a standard encoding, it just won't work.  
 
 
 Hey Mike,
 
 Thanks for your reply. That makes sense.
 
 An alternative work around (I presume) would be to install the computer 
 modern unicode fonts (I made sure to install the ttf version). However, I'm 
 having trouble getting MPL to find the fonts.
 
 The installed font is listed when calling 
 `mpl.font_manager.OSXInstalledFonts()`, but it's not found when calling 
 `mpl.font_manager.findfont` (with various names that would make sense: 
 cmunrm, CMU Serif, etc.)
 
 Any ideas on what I'm doing wrong?
 
 Sorry, I meant to reply to the list.
 
 After clearing the fontlist cache, I was able to get this fix working.
 
 Just to summarize:
 
 * download unicode version of computer modern fonts 
 (http://sourceforge.net/projects/cm-unicode/files/)---make sure to get the 
 ttf version
 
 * clear out the fontlist cache (rm ~/.matplotlib/fontList.cache)
 
 * add the following to ~/matplotlib/matplotlibrc:
 
 font.family: serif
 font.serif: CMU Serif
 
 * alternatively, you could leave the default as sans serif and use the 
 computer modern sans serif (unicode version):
 
 font.sans-serif: CMU Sans Serif
 
 These changes produce plots where the size of normal text matches that of 
 mathtext.
 
 Thanks for you help, Mike!
 
 -Tony
 

Umm, ... last email on this topic, I promise.

Is there any reason the font family rc parameter is case sensitive, while the 
findfont input is case insensitive? In other words, replacing

 font.serif: CMU Serif

with

 font.serif: cmu serif

does not work. On the other hand, both of the following work:

 mpl.font_manager.findfont('cmu serif')
 mpl.font_manager.findfont('CMU Serif')

This caused me problems when debugging my earlier font troubles.

Best,
-Tony

--
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] custom color cycle from cmap

2010-04-08 Thread Tony S Yu

On Apr 8, 2010, at 8:13 AM, KrishnaPribadi wrote:

 
 Hi, 
 I'm trying to plot a set of lines, 12 to be exact, and the default color
 cycle only supports 8 or 9 distinct colors. That said, I looked up the color
 maps and segmented it using 12 constant intervals with the hope of getting
 12 distinct colors.
 
 The problem I'm running in to is that some of the line colors I get are too
 close to each other. This is because come shades in the colormap have a
 broader spectrum than others.
 
 Here is my code to set my custom default color cycle:
 
import matplotlib as mpl
cmap = mpl.cm.get_cmap(name='spectral') #I gues we can also use
 hsv or gist_rainbow
nColors = 12 #number of colors
incr = 0.9 / nColors
 
self.mycolors = []
for i in np.arange(0,0.9,incr):
self.mycolors.append(cmap(i))

you could replace the loop with a list comprehension:

 mycolors = [cmap(i) for i in np.arange(0,0.9,incr)]

Also, arange may not be a great fit for this task; maybe linspace would work 
better:

 mycolors = [cmap(i) for i in np.linspace(0, 0.9, nColors)]

This allows you to eliminate the assignment of `incr`. Note: the above colormap 
is different than that created by arange because linspace includes the 
endpoint, while arange doesn't.

Hope that helps,
-Tony

 
mpl.axes.set_default_color_cycle(self.mycolors)
 
 Can anyone suggest a cleaner method? Or is there perhaps an existing class
 to provide distinct color lines?
 
 Thanks,
 Krishna

--
Download Intel#174; Parallel Studio Eval
Try the new software tools for yourself. Speed compiling, find bugs
proactively, and fine-tune applications for parallel performance.
See why Intel Parallel Studio got high marks during beta.
http://p.sf.net/sfu/intel-sw-dev
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Bug: string.letters

2010-03-09 Thread Tony S Yu

On Mar 9, 2010, at 1:22 PM, John Hunter wrote:

 On Tue, Mar 9, 2010 at 12:16 PM, Eric Firing efir...@hawaii.edu wrote:
 
 Bizarre!  I can reproduce it with python 2.6 (ubuntu 9.10) and mpl from
 svn.  I have done a little grepping and other exploration, but have
 completely failed to find where this change is occurring.
 
 
 
 cbook imports locale -- may be implicated:
 
 string.letters¶
The concatenation of the strings lowercase and uppercase described
 below. The specific value is locale-dependent, and will be updated
 when locale.setlocale() is called.
 
 See if simply importing locale first has the same effect.


It seems to be an interaction between numpy and locale. I can reproduce the 
problem with:

 import locale
 import numpy as np

 preferredencoding = locale.getpreferredencoding()

 import string
 print string.letters

The bug disappears after removing the numpy import.

-Tony


--
Download Intel#174; Parallel Studio Eval
Try the new software tools for yourself. Speed compiling, find bugs
proactively, and fine-tune applications for parallel performance.
See why Intel Parallel Studio got high marks during beta.
http://p.sf.net/sfu/intel-sw-dev
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] define color cycle in matplotlibrc

2009-12-29 Thread Tony S Yu
 
 Tony S Yu wrote:
 On Dec 29, 2009, at 3:35 AM, Dominik Szczerba wrote:
 Tony S Yu wrote:
 Hey Dominik,
 
 I'd also like to see the default color_cycle be customizeable. But, if
 I'm not mistaken, this approach doesn't quite do what you want (at least
 it doesn't on a recent version of mpl). The problem is that the color
 given by lines.color (rcParam) sort of overrides the first color in the
 specified color cycle (see
 ``_process_plot_var_args._clear_color_cycle`` in  axes.py). 
 
 It seems important for lines.color and the first color in the color
 cycle to match since this matching is also enforced in
 ``axes.set_default_color_cycle``, except in reverse (the first color in
 the color cycle overrides line.color). If both lines.color and
 axes.color_cycle (or maybe lines.color_cycle) are rcParams, there would
 be issues with how to match the two (e.g. which takes precedence if they
 differ).
 
 As I said earlier, I'd like to see this change made, but I think it may
 change the current behavior. Maybe a mpl developer could weigh in?
 
 -Tony
 Hi Tony,
 You are correct, line color overrides the first cycle color. That does
 not appear a very happy choice to me but this way or another you can
 still specify BOTH lines.color and the cycle in the param file to get
 whatever you want, no?
 
 Dominik
 
 Yup, that should do exactly what you want. But, since it's a bit of a hack 
 (you should only need to make 1 change to matplotlibrc), I doubt this patch 
 would be appropriate for the main distribution. 
 
 Ideally, we'd need to figure out if the matplotlibrc changes 1) only 
 lines.color and make this the first color in color_cycle, 2) only 
 lines.color_cycle and make the first color override lines.color, or 3) both 
 lines.color and lines.color_cycle (behavior unknown if colors don't match). 
 Unfortunately, I don't see an easy way to tell if rcParams have been changed 
 from their default values. 
 
 Hi Tony,
 My patches (there were two!) remove the badly hardcoded definition of
 defaultColors in axes.py and instead define default axes.color_cycle in
 rcsetup.py (defaulting it to the already established color array
 ['b','g','r','c','m','y','k']). Now, in axes.py, defaultColors are taken
 from rcParams, and not a hardcoded array, so unless you modify your own
 rc file, you will get the old behavior. It is if and only if you define
 your color_cycle in your own rc file that will do anything new. I do not
 see how this introduces any incompatibilities.
 Dominik

Sorry for the confusion. I wasn't saying your patches introduce 
incompatibilities, but I did say that their behavior is not ideal. For example, 
your matplotlibrc requires *both* lines.color_cycle : w, w, w, w, w, w 
(actually I think you only need one w,) *and* lines.color : w. Ideally (at 
least IMO), I should only need to set the color cycle, and it was surprising to 
me (surprises = bad) that I'd have to also set lines.color

The incompatibilities I spoke of would only be true if you went with my 
suggestion to deprecate lines.color.

-T

--
This SF.Net email is sponsored by the Verizon Developer Community
Take advantage of Verizon's best-in-class app development support
A streamlined, 14 day to market process makes app distribution fast and easy
Join now and get one step closer to millions of Verizon customers
http://p.sf.net/sfu/verizon-dev2dev ___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] define color cycle in matplotlibrc

2009-12-28 Thread Tony S Yu

On Dec 24, 2009, at 4:21 AM, Dominik Szczerba wrote:
 OK I started hacking and added a color_cycle property to matplotlibrc.
 Would you be so kind to add this fix to the official version? Thanks!
 Dominik
 
 $ diff -w axes.py axes.py.org
 135,137c135
  # DSZ take defaultColors from rcParams
  # defaultColors = ['b','g','r','c','m','y','k']
  defaultColors = rcParams['axes.color_cycle']
 - ---
defaultColors = ['b','g','r','c','m','y','k']
 
 
 $ diff -w rcsetup.py rcsetup.py.org
 442,443d441
  # DSZ add color_cycle property
  'axes.color_cycle' : [['b','g','r','c','m','y','k'],
 validate_stringlist],
 
 
 
 Add to custom matplotlibrc as e.g.:
 
 axes.color_cycle: w, w, w, w, w, w, w
 

Hey Dominik,

I'd also like to see the default color_cycle be customizeable. But, if I'm not 
mistaken, this approach doesn't quite do what you want (at least it doesn't on 
a recent version of mpl). The problem is that the color given by lines.color 
(rcParam) sort of overrides the first color in the specified color cycle (see 
``_process_plot_var_args._clear_color_cycle`` in  axes.py). 

It seems important for lines.color and the first color in the color cycle to 
match since this matching is also enforced in ``axes.set_default_color_cycle``, 
except in reverse (the first color in the color cycle overrides line.color). If 
both lines.color and axes.color_cycle (or maybe lines.color_cycle) are 
rcParams, there would be issues with how to match the two (e.g. which takes 
precedence if they differ).

As I said earlier, I'd like to see this change made, but I think it may change 
the current behavior. Maybe a mpl developer could weigh in?

-Tony


--
This SF.Net email is sponsored by the Verizon Developer Community
Take advantage of Verizon's best-in-class app development support
A streamlined, 14 day to market process makes app distribution fast and easy
Join now and get one step closer to millions of Verizon customers
http://p.sf.net/sfu/verizon-dev2dev ___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Plotting curves filled with nonuniform color patch

2009-12-03 Thread Tony S Yu

On Dec 3, 2009, at 3:58 PM, Jae-Joon Lee wrote:

 line 1486 of _backend_agg.cpp says
 
  /* TODO: Support clip paths */
 
 So, it seems that, apparently, clipping with arbitrary path has not
 been implemented yet for gouraud shading (pcolormesh will be properly
 clipped if shading is not used).
 I hope Michael pick this up some time soon.
 
 Meanwhile, you may open a feature request ticket on this.
 
 Regards,
 
 -JJ


Hey Jae-Joon,

Thanks for digging into this. Feature request added.

By the way, I was looking through the feature requests and noticed an open 
feature request (ID: 2112292) that was satisfied by the addition of spines in 
the last major release. Just an FYI, if someone with privileges wants to close 
the request.

Thanks,
-Tony
--
Join us December 9, 2009 for the Red Hat Virtual Experience,
a free event focused on virtualization and cloud computing. 
Attend in-depth sessions from your desk. Your couch. Anywhere.
http://p.sf.net/sfu/redhat-sfdev2dev
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Plotting curves filled with nonuniform color patch

2009-12-02 Thread Tony S Yu

On Dec 2, 2009, at 3:53 PM, Tony S Yu wrote:

 Hi,
 
 I'm having hard time understanding some of the differences between functions 
 used to plot color patches (not sure what to call them).
 
 I'm trying to fill a curve with a nonuniform color patch (like fill or 
 fill_between but the color in the patch varies). I've attached code that 
 almost does what I want; my question concerns the color patch (which is 
 created by the call to plt.pcolor in the code below). I'd like to have 
 nonuniform grid spacing in the color values, and also shading (i.e. 
 interpolation of color between points). Here's what I understand:
 
 pcolor: allows nonuniform grid spacing, but it doesn't do shading.
 
 imshow: allows color shading, but requires uniform spacing
 
 pcolormesh: allows color interpolation and nonuniform grid spacing
 
 pcolormesh seems like the ideal candidate, but when I replace pcolor with 
 pcolormesh (code commented out below pcolor call), the path doesn't get 
 clipped by set_clip_path (but no errors are raised); in other words, the 
 color shading fills the entire plot area. Is this a bug?
 
 Is there a way of making this plot work that I've overlooked?
 
 Thanks!
 -Tony


Nevermind, I found NonUniformImage after some digging. The working code is 
attached below if anyone is interested. 

If anyone knows the answer, I'm still curious if the clipping behavior for 
pcolormesh is a bug.

Thanks,
-Tony



# example code

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import NonUniformImage


def nonuniform_imshow(x, y, C, **kwargs):
Plot image with nonuniform pixel spacing.

This function is a convenience method for calling image.NonUniformImage.

ax = plt.gca()
im = NonUniformImage(ax, **kwargs)
im.set_data(x, y, C)
ax.images.append(im)
return im


def plot_filled_curve(x, y, c):
Plot curve filled with linear color gradient

Parameters
--
x, y : arrays
points describing curve
c : array
color values underneath curve. Must match the lengths of `x` and `y`.

# add end points so that fill extends to the x-axis
x_closed = np.concatenate([x[:1], x, x[-1:]])
y_closed = np.concatenate([[0], y, [0]])
# fill between doesn't work here b/c it returns a PolyCollection, plus it
# adds the lower half of the plot by adding a Rect with a border
patch, = plt.fill(x_closed, y_closed, facecolor='none')
im = nonuniform_imshow(x, [0, y.max()], np.vstack((c, c)), 
   interpolation='bilinear', cmap=plt.cm.gray)
im.set_clip_path(patch)

if __name__ == '__main__':
line = np.linspace(0, 1, 6)
x = np.hstack((line, [1, 2]))
y = np.hstack((line**2, [1, 1]))
c = np.hstack((line, [0, 0]))
plot_filled_curve(x, y, c)
plt.show()



--
Join us December 9, 2009 for the Red Hat Virtual Experience,
a free event focused on virtualization and cloud computing. 
Attend in-depth sessions from your desk. Your couch. Anywhere.
http://p.sf.net/sfu/redhat-sfdev2dev
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] overriding Collections.get_transform weirdness

2009-11-12 Thread Tony S Yu

On Nov 12, 2009, at 8:16 AM, Michael Droettboom wrote:

 Thanks for looking into this further.  Can you file a bug with this  
 script that appears differently in the PDF/PS/SVG/Agg backends vs.  
 Mac OS X?

Bug filed. Thanks for your response.

-Tony


 Cheers,
 Mike

 Tony S Yu wrote:

 On Nov 11, 2009, at 1:33 PM, Michael Droettboom wrote:

 Which older revision (or release) worked as you expected?

 After some digging, I think this issue is caused by an error in the  
 macosx backend (everything works fine with tkagg, qt4agg, and agg).  
 Oddly enough, calling savefig(), instead of show(), with the macosx  
 backend creates the correct plot, but calling savefig() after show 
 () does not.

 I'm actually not sure if my code worked for older revisions of the  
 macosx backend (I may have had a different default backend before).  
 The transform code doesn't work with revisions between 7950 and  
 7625; older versions break the macosx backend on my system (OS X  
 10.6.1).

 -Tony



--
Let Crystal Reports handle the reporting - Free Crystal Reports 2008 30-Day 
trial. Simplify your report design, integration and deployment - and focus on 
what you do best, core application coding. Discover what's new with
Crystal Reports now.  http://p.sf.net/sfu/bobj-july
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] overriding Collections.get_transform weirdness

2009-11-11 Thread Tony S Yu
Hi,

Awhile back, Jae-Joon helped me transform collection sizes from points  
to data values by overriding the `get_transform` method of a  
RegularPolyCollection (see example code below).

When I tried the code today, the collection didn't appear on the plot.  
Removing the get_transform method below brings the collection back,  
but of course, the sizes are not what I want.

Some simple testing suggests that changing the transform returned by  
`get_transform` changes the offsets of the collection items. In other  
words, the transform originally (i.e. in some older revision) modified  
only the scale of collection items, but now appears to modify both the  
scale and offset.

Is there a way to modify only the scale of collection items?

Thanks,
-Tony

BTW, I'm on svn r7950.

#-
# The squares will not show up with the code below
# Comment out the get_transform method to see squares
# Change scale_x and scale_y to values close to 1 to see how they  
change both scale and offset

class SquareCollection(collections.RegularPolyCollection):
Return a collection of squares.

def __init__(self, **kwargs):
super(SquareCollection, self).__init__(4, rotation=np.pi/4.,  
**kwargs)

def get_transform(self):
Return transform scaling circle areas to data space.
ax = self.axes
pts2pixels = 72.0 / ax.figure.dpi
scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width
scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height
return transforms.Affine2D().scale(scale_x, scale_y)

ax = plt.gca()
circle_areas = np.pi * np.ones(4)
xy = [(0, 0), (0, 1), (1, 0), (1, 1)]
squares = SquareCollection(sizes=circle_areas,
   offsets=xy, transOffset=ax.transData,
   facecolor='black')
ax.add_collection(squares, autolim=True)
plt.axis([-0.5, 1.5, -0.5, 1.5])
plt.show()



--
Let Crystal Reports handle the reporting - Free Crystal Reports 2008 30-Day 
trial. Simplify your report design, integration and deployment - and focus on 
what you do best, core application coding. Discover what's new with
Crystal Reports now.  http://p.sf.net/sfu/bobj-july
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] overriding Collections.get_transform weirdness

2009-11-11 Thread Tony S Yu

On Nov 11, 2009, at 1:33 PM, Michael Droettboom wrote:

 Which older revision (or release) worked as you expected?

After some digging, I think this issue is caused by an error in the  
macosx backend (everything works fine with tkagg, qt4agg, and agg).  
Oddly enough, calling savefig(), instead of show(), with the macosx  
backend creates the correct plot, but calling savefig() after show()  
does not.

I'm actually not sure if my code worked for older revisions of the  
macosx backend (I may have had a different default backend before).  
The transform code doesn't work with revisions between 7950 and 7625;  
older versions break the macosx backend on my system (OS X 10.6.1).

-Tony



 Mike

 Tony S Yu wrote:
 Hi,

 Awhile back, Jae-Joon helped me transform collection sizes from  
 points  to data values by overriding the `get_transform` method of  
 a  RegularPolyCollection (see example code below).

 When I tried the code today, the collection didn't appear on the  
 plot.  Removing the get_transform method below brings the  
 collection back,  but of course, the sizes are not what I want.

 Some simple testing suggests that changing the transform returned  
 by  `get_transform` changes the offsets of the collection items. In  
 other  words, the transform originally (i.e. in some older  
 revision) modified  only the scale of collection items, but now  
 appears to modify both the  scale and offset.

 Is there a way to modify only the scale of collection items?

 Thanks,
 -Tony

 BTW, I'm on svn r7950.

 #-
 # The squares will not show up with the code below
 # Comment out the get_transform method to see squares
 # Change scale_x and scale_y to values close to 1 to see how they   
 change both scale and offset

 class SquareCollection(collections.RegularPolyCollection):
Return a collection of squares.

def __init__(self, **kwargs):
super(SquareCollection, self).__init__(4, rotation=np.pi/ 
 4.,  **kwargs)

def get_transform(self):
Return transform scaling circle areas to data space.
ax = self.axes
pts2pixels = 72.0 / ax.figure.dpi
scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width
scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height
return transforms.Affine2D().scale(scale_x, scale_y)

 ax = plt.gca()
 circle_areas = np.pi * np.ones(4)
 xy = [(0, 0), (0, 1), (1, 0), (1, 1)]
 squares = SquareCollection(sizes=circle_areas,
   offsets=xy, transOffset=ax.transData,
   facecolor='black')
 ax.add_collection(squares, autolim=True)
 plt.axis([-0.5, 1.5, -0.5, 1.5])
 plt.show()



 --
 Let Crystal Reports handle the reporting - Free Crystal Reports  
 2008 30-Day trial. Simplify your report design, integration and  
 deployment - and focus on what you do best, core application  
 coding. Discover what's new with
 Crystal Reports now.  http://p.sf.net/sfu/bobj-july
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


 -- 
 Michael Droettboom
 Science Software Branch
 Operations and Engineering Division
 Space Telescope Science Institute
 Operated by AURA for NASA



--
Let Crystal Reports handle the reporting - Free Crystal Reports 2008 30-Day 
trial. Simplify your report design, integration and deployment - and focus on 
what you do best, core application coding. Discover what's new with
Crystal Reports now.  http://p.sf.net/sfu/bobj-july
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Location matplotlibrc file on my Mac

2009-11-03 Thread Tony S Yu

On Nov 3, 2009, at 3:08 PM, phob...@geosyntec.com phob...@geosyntec.com 
  wrote:
 -Original Message-
 From: Tony S Yu [mailto:ton...@mit.edu]
 Hi Paul,

 I think your matplotlibrc file should be put in:
 /Users/paul/.matplotlib

 -Tony

 Thanks Tony, I'll give that a shot. Shouldn't keeping it in my  
 current working directory work as well? One of the great things  
 about using the matplotlibrc file on my Windows machine is that I  
 can keep different files for different projects.


(Paul, I hope you don't mind if I bring this bump this back to the  
list).

Apparently I skimmed your original email and didn't see that you tried  
putting the file in your working directory. That should work. (My  
original response is still appropriate for a global rc file.)

As suggested on the mpl website (specifically: 
http://matplotlib.sourceforge.net/users/customizing.html 
), you can try printing out the path of the rc file being used by  
adding the following to your script:

  import matplotlib
  print matplotlib.matplotlib_fname()

Also, you may want to check that the working directory is where you  
think it is. For example, if you run a script from the terminal as:

$ python ~/path/to/file.py

Your working directory is '~' and not '~/path/to/'---so matplotlibrc  
file located in the same directory as file.py would not be in the  
working directory.

Otherwise, I have no idea why the matplotlibrc is not being found in  
the working directory.

Best,
-Tony


--
Come build with us! The BlackBerry(R) Developer Conference in SF, CA
is the only developer event you need to attend this year. Jumpstart your
developing skills, take BlackBerry mobile applications to market and stay 
ahead of the curve. Join us from November 9 - 12, 2009. Register now!
http://p.sf.net/sfu/devconference
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Location matplotlibrc file on my Mac

2009-11-03 Thread Tony S Yu

On Nov 3, 2009, at 1:11 PM, phob...@geosyntec.com wrote:

 Hey everyone,

 The existence of the matplotlibrc file is one reason I like MPL so  
 much. I won't go into the convoluted work flow I had for getting my  
 MATLAB figures completely processed in TeX, but it was nasty.

 On my Windows machine, I've used it with great success. But I can't  
 get my Mac (OS 10.5) to see it at all. I've put it in my current  
 working directory, in /Library/Frameworks/.../mpl_data, and in / 
 Users/paul. I've confirmed that those directories are in my sys.path  
 variable as well. Nothing seems to work.


Hi Paul,

I think your matplotlibrc file should be put in: /Users/paul/.matplotlib

-Tony

--
Come build with us! The BlackBerry(R) Developer Conference in SF, CA
is the only developer event you need to attend this year. Jumpstart your
developing skills, take BlackBerry mobile applications to market and stay 
ahead of the curve. Join us from November 9 - 12, 2009. Register now!
http://p.sf.net/sfu/devconference
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] polar filled plot

2009-10-18 Thread Tony S Yu
Hi Giovanni,

Radar plots haven't been added to the core functionality of  
matplotlib, but there's an example of a custom radar chart class on  
the mpl website:
http://matplotlib.sourceforge.net/examples/api/radar_chart.html

Best,
-Tony


On Oct 17, 2009, at 9:33 AM, Giovanni Bacci wrote:


  Hi all. I'd like to know if it's possible to obtain a radar plot like
 this: http://code.google.com/intl/en/apis/chart/types.html#radar (the
 filled one, with cht=rs) with matplotlib. I'm using matplotlib version
 0.98.5

 Thanks,
  Giovanni

 --
 Come build with us! The BlackBerry(R) Developer Conference in SF, CA
 is the only developer event you need to attend this year. Jumpstart  
 your
 developing skills, take BlackBerry mobile applications to market and  
 stay
 ahead of the curve. Join us from November 9 - 12, 2009. Register now!
 http://p.sf.net/sfu/devconference
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
Come build with us! The BlackBerry(R) Developer Conference in SF, CA
is the only developer event you need to attend this year. Jumpstart your
developing skills, take BlackBerry mobile applications to market and stay 
ahead of the curve. Join us from November 9 - 12, 2009. Register now!
http://p.sf.net/sfu/devconference
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Simple pattern recognition

2009-09-16 Thread Tony S Yu


On Sep 16, 2009, at 8:22 PM, Gökhan Sever wrote:


Hello all,

I want to be able to count predefined simple rectangle shapes on an  
image as shown like in this one: http://img7.imageshack.us/img7/2327/particles.png


Which is in my case to count all the blue pixels (they are ice-snow  
flake shadows in reality) in one of the column.


What is the way to automate this task, which library or technique  
should I study to tackle it.


You should check out the ndimage subpackage in scipy.

This tutorial should help you get started:
http://docs.scipy.org/doc/scipy/reference/tutorial/ndimage.html
The section on segmentation and labeling will be particularly useful  
for you.


Best,
-Tony

--
Come build with us! The BlackBerryreg; Developer Conference in SF, CA
is the only developer event you need to attend this year. Jumpstart your
developing skills, take BlackBerry mobile applications to market and stay 
ahead of the curve. Join us from November 9#45;12, 2009. Register now#33;
http://p.sf.net/sfu/devconf___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Design questions

2009-07-31 Thread Tony S Yu

On Jul 30, 2009, at 5:16 PM, Gewton Jhames wrote:


Anyone?

On Tue, Jul 28, 2009 at 3:23 PM, Gewton Jhames gjha...@gmail.com  
wrote:

Guys, there is the code.
On Tue, Jul 28, 2009 at 3:13 PM, Gewton Jhames gjha...@gmail.com  
wrote:
Jae-Joon Lee, savefig(file.png, bbox_inches=tight) doesn't work  
too.



On Mon, Jul 27, 2009 at 7:00 PM, Jae-Joon Lee lee.j.j...@gmail.com  
wrote:

[Snip]
On Mon, Jul 27, 2009 at 4:06 PM, Gewton Jhamesgjha...@gmail.com  
wrote:

On the other hand, there is some crude support for trimming, i.e.,
reducing the figure size while the axes area fixed.

savefig(file.png, bbox_inches=tight)

Note that the figure size of the saved output is only affected. This
does not change the figure displayed on the screen.

Regards,

-JJ



Jae-Joon's suggestion worked for me (using your code). Since this  
feature is pretty new, it may depend on the version you're using (I'm  
using the latest from svn).


I couldn't get `autoscale_view` to work either. However,  
`subplots_adjust` should work with a little tweaking. Instead of the  
dimensions John gave, try plt.subplots_adjust(left=0.07, right=0.99).  
These dimensions may show up differently on your system, so try  
tweaking these values.


Best,
-T--
Let Crystal Reports handle the reporting - Free Crystal Reports 2008 30-Day 
trial. Simplify your report design, integration and deployment - and focus on 
what you do best, core application coding. Discover what's new with 
Crystal Reports now.  http://p.sf.net/sfu/bobj-july___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Radar / Spider Chars

2009-07-28 Thread Tony S Yu



Josh Hemann wrote:

Tony,

I know this is a year later but your code was hugely helpful to me  
last

week, so thank you



I'm glad you found it helpful.


On Jul 28, 2009, at 12:56 PM, Michael Droettboom wrote:

Would you (Josh and Tony) be amenable to us including this in the  
set of
examples?  It would make it easier for users to find it.   
Eventually, it

might be nice to include this as a core plotting command, but in the
meantime, I think it would still be useful as-is.

Mike


Hey Mike,

I'm always happy to contribute what little I can to matplotlib.  
However, if it's going to be an official example, it should be cleaned  
up a bit (see attached). Summary of changes.


* My original example (i.e. not Josh's fault) didn't play well with  
namespaces (i.e. from pylab import *). This has been changed to use  
the proper imports (i.e. np and plt).


* Also, there were problems with rgrids when I originally wrote the  
code, which has since been fixed (at least on trunk it is). This  
eliminates the need to manually draw a grid.


* I made a few other clean ups for clarity. (Josh: I hope you don't  
mind, I switched the data for f4_base and f5_base so that I could  
remove the associated comment.)


* Final note. The polygon frame no longer works properly and I  
couldn't really figure out how to fix it.


Best,
-Tony


import numpy as np

import matplotlib.pyplot as plt
from matplotlib.projections.polar import PolarAxes 
from matplotlib.projections import register_projection 

def radar_factory(num_vars, frame='circle'): 
Create a radar chart with `num_vars` axes. 
# calculate evenly-spaced axis angles 
theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars) 
# rotate theta such that the first axis is at the top 
theta += np.pi/2 

def draw_poly_frame(self, x0, y0, r): 
# TODO: use transforms to convert (x, y) to (r, theta)
verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta] 
return plt.Polygon(verts, closed=True, edgecolor='k') 

def draw_circle_frame(self, x0, y0, r): 
return plt.Circle((x0, y0), r) 

frame_dict = {'polygon': draw_poly_frame, 'circle': draw_circle_frame} 
if frame not in frame_dict: 
raise ValueError, 'unknown value for `frame`: %s' % frame 

class RadarAxes(PolarAxes): 
Class for creating a radar chart (a.k.a. a spider or star chart) 

http://en.wikipedia.org/wiki/Radar_chart 
 
name = 'radar' 
# use 1 line segment to connect specified points 
RESOLUTION = 1 
# define draw_frame method 
draw_frame = frame_dict[frame] 

def fill(self, *args, **kwargs): 
Override fill so that line is closed by default 
closed = kwargs.pop('closed', True) 
return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) 

def plot(self, *args, **kwargs): 
Override plot so that line is closed by default 
lines = super(RadarAxes, self).plot(*args, **kwargs) 
for line in lines: 
self._close_line(line) 

def _close_line(self, line): 
x, y = line.get_data() 
# FIXME: markers at x[0], y[0] get doubled-up 
if x[0] != x[-1]: 
x = np.concatenate((x, [x[0]])) 
y = np.concatenate((y, [y[0]])) 
line.set_data(x, y) 

def set_varlabels(self, labels): 
self.set_thetagrids(theta * 180/np.pi, labels) 

def _gen_axes_patch(self): 
x0, y0 = (0.5, 0.5) 
r = 0.5 
return self.draw_frame(x0, y0, r)

register_projection(RadarAxes) 
return theta 


if __name__ == '__main__': 
#The following data is from the Denver Aerosol Sources and Health study. 
#See  doi:10.1016/j.atmosenv.2008.12.017
#
#The data are pollution source profile estimates for five modeled pollution
#sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical species.
#The radar charts are experimented with here to see if we can nicely 
#visualize how the modeled source profiles change across four scenarios:
#  1) No gas-phase species present, just seven particulate counts on
# Sulfate
# Nitrate
# Elemental Carbon (EC)
# Organic Carbon fraction 1 (OC)
# Organic Carbon fraction 2 (OC2)
# Organic Carbon fraction 3 (OC3)
# Pyrolized Organic Carbon (OP)
#  2)Inclusion of gas-phase specie carbon monoxide (CO) 
#  3)Inclusion of gas-phase specie ozone (O3). 
#  4)Inclusion of both gas-phase speciesis present...
N = 9
theta = radar_factory(N)
spoke_labels = ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 
'O3']
f1_base = [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00]
f1_CO =   [0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 

Re: [Matplotlib-users] Radar / Spider Chars [bug?]

2009-07-28 Thread Tony S Yu

On Jul 28, 2009, at 4:53 PM, Josh Hemann wrote:

 One small nit: I
 don't see any code to set the color or alpha level of the grid  
 lines. In my
 example, I set the color to be a light grey because I wanted the  
 grid lines
 to be seen but not be distracting from the data. Just a preference.


Good point. It turns out the grid lines are already pretty faint on my  
computer, so I didn't need to adjust this. The most obvious thing to  
do is replace

  plt.rgrids(radial_grid)

with

  lines, labels = plt.rgrids(radial_grid)
  plt.setp(lines, alpha=0.4)

**However**, this modification doesn't help. In fact, nothing I did to  
the gridlines changed their appearance. Out of frustration, I went to  
the code and found that `rgrids` calls *get_ticklines* instead of  
*get_gridlines*. My guess is that this is a typo, but there may be a  
compelling reason to return the tick lines. If that's not the case,  
here's a ridiculously simple patch:

Index: lib/matplotlib/projections/polar.py
===
--- lib/matplotlib/projections/polar.py (revision 7300)
+++ lib/matplotlib/projections/polar.py (working copy)
@@ -397,7 +397,7 @@
  self._r_label2_position.clear().translate(angle, -self._rpad  
* rmax)
  for t in self.yaxis.get_ticklabels():
  t.update(kwargs)
-return self.yaxis.get_ticklines(), self.yaxis.get_ticklabels()
+return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels()

  set_rgrids.__doc__ = cbook.dedent(set_rgrids.__doc__) % kwdocd


--
Let Crystal Reports handle the reporting - Free Crystal Reports 2008 30-Day 
trial. Simplify your report design, integration and deployment - and focus on 
what you do best, core application coding. Discover what's new with 
Crystal Reports now.  http://p.sf.net/sfu/bobj-july
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] question about setting colors of lines using colormap

2009-07-14 Thread Tony S Yu
Not too long ago, I posted an example of this to the list. The code  
near the bottom of that thread is a little more general than the one  
at the top and shows, three different ways to cycle through the colors  
of a colormap.


Hope that helps,
-Tony


On Jul 14, 2009, at 9:51 AM, per freem wrote:


Hi all,

i would like to set the colors of the lines i plot (using the plot  
function) to go from red to blue, in evenly spaced interval. that  
is, imagine a color map from red to green, where i plot n-many  
lines, each receiving a color from this color map, starting at the  
red end and going to green.


the docs say how to set the color cycle of lines set by plot, using:

matplotlib.axes.set_default_color_cycle(['r', 'y', 'g', 'b'])

but this only allows me to use named colors, and here i am looking  
to use shades from red to green.
my question is: first, how can i generate N evenly spaced colors  
from the red spectrum to the green spectrum? and two, how can i make  
it so plot uses these colors for its line plots?


thanks very much.
--
Enter the BlackBerry Developer Challenge
This is your chance to win up to $100,000 in prizes! For a limited  
time,
vendors submitting new applications to BlackBerry App World(TM) will  
have
the opportunity to enter the BlackBerry Developer Challenge. See  
full prize

details at: 
http://p.sf.net/sfu/Challenge___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
Enter the BlackBerry Developer Challenge  
This is your chance to win up to $100,000 in prizes! For a limited time, 
vendors submitting new applications to BlackBerry App World(TM) will have
the opportunity to enter the BlackBerry Developer Challenge. See full prize  
details at: http://p.sf.net/sfu/Challenge___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] question about setting colors of lines using colormap

2009-07-14 Thread Tony S Yu


On Jul 14, 2009, at 3:12 PM, per freem wrote:


Hi Tony,

thanks for the pointer.  that code does not run for me, it generates  
the following error:


ttributeErrorTraceback (most recent call  
last)






/Library/Python/2.5/site-packages/matplotlib/rcsetup.pyc in  
validate_color(s)

160 def validate_color(s):
161 'return a valid color arg'
-- 162 if s.lower() == 'none':
163 return 'None'
164 if is_color_like(s):

AttributeError: 'list' object has no attribute 'lower'
WARNING: Failure executing file: color_cycle.py

any idea what might be wrong?


Hmm, it looks like there was a fix added a couple of months ago (svn  
revision 7164). If you're on trunk, then updating it should fix this  
problem. If you're not on trunk: I don't think any official releases  
have occurred since this fix, so I don't think updating to the last  
official release will help.


In any case, I think this error only affects the ``cycle_cmap``  
function in the code (calls to ``cmap_intervals`` should work fine).  
If you comment out the 4 lines of code after the comment Change the  
default color cycle, I believe everything should work fine.


-Tony--
Enter the BlackBerry Developer Challenge  
This is your chance to win up to $100,000 in prizes! For a limited time, 
vendors submitting new applications to BlackBerry App World(TM) will have
the opportunity to enter the BlackBerry Developer Challenge. See full prize  
details at: http://p.sf.net/sfu/Challenge___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Help with transforms of collections

2009-06-22 Thread Tony S Yu

On Jun 22, 2009, at 2:57 PM, Jae-Joon Lee wrote:
 The easiest solution I can think of is doing some monkey patching.


 import matplotlib.pyplot as plt
 import matplotlib.transforms as transforms
 import numpy as np
 fig = plt.figure()
 ax = fig.add_subplot(111)
 x = [0.25, 0.75, 0.25, 0.75]
 y = [0.25, 0.25, 0.75, 0.75]
 r = 0.1 * np.ones(4)
 col = plt.scatter(x, y, np.pi*r**2)


 from matplotlib.collections import RegularPolyCollection
 class RegularPolyCollection2(RegularPolyCollection):
def get_transform(self):
ax = self.axes

sc_x = ax.bbox.width / ax.viewLim.width
sc_y = ax.bbox.height / ax.viewLim.height

return transforms.Affine2D().scale(sc_x, sc_y)

 col.__class__ = RegularPolyCollection2

 plt.axis('equal')
 plt.show()

Thanks Jae-Joon! This is exactly what I was looking for.

-Tony

--
Are you an open source citizen? Join us for the Open Source Bridge conference!
Portland, OR, June 17-19. Two days of sessions, one day of unconference: $250.
Need another reason to go? 24-hour hacker lounge. Register today!
http://ad.doubleclick.net/clk;215844324;13503038;v?http://opensourcebridge.org
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] Help with transforms of collections

2009-06-18 Thread Tony S Yu
I'd like to plot a collection and scale the size of the collection  
elements in relation to the data. My guess is that I need to use the  
data transformation (ax.transData) since I would like the size of the  
collection elements altered when zooming in/out.

Unfortunately, my attempt has led to weird results: the collection  
offsets are shifted from the desired coordinates when using  
ax.transData. Weirder still: the collection elements move *relative to  
the data coordinates* when panning the figure.

I suspect that setting the collection transform to ax.transData is  
somehow applying some part of the transform twice. Does anyone know  
what I'm doing wrong here and how I can fix this?

Thanks!
-Tony

Attached is a toy example of what I'm trying to do. The radii of the  
circles are plotted correctly, but notice the x, y coordinates don't  
match the circle centers in the plot. Also, try panning the plot and  
watch as the circles move relative to the tick marks.


  import matplotlib.pyplot as plt
  import matplotlib.transforms as transforms
  import numpy as np
  fig = plt.figure()
  ax = fig.add_subplot(111)
  x = [0.25, 0.75, 0.25, 0.75]
  y = [0.25, 0.25, 0.75, 0.75]
  r = 0.1 * np.ones(4)
  col = plt.scatter(x, y, np.pi*r**2)
  pts2pixels = transforms.Affine2D().scale(72.0/fig.dpi)
  col.set_transform(pts2pixels + ax.transData)
  plt.axis('equal')
  plt.show()

--
Crystal Reports - New Free Runtime and 30 Day Trial
Check out the new simplified licensing option that enables unlimited
royalty-free distribution of the report engine for externally facing 
server and web deployment.
http://p.sf.net/sfu/businessobjects
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Where to post examples (specifically, one that may be useful for time-evolution plots)

2009-06-06 Thread Tony S Yu


On Jun 6, 2009, at 9:34 AM, John Hunter wrote:

I'm happy to post this example in the examples dir, where it will
automatically get picked up in the website gallery and examples dir.


That'd be great!


The scipy cookbook is fine too, but I would prefer that a little mini
tutorial be written in rest explaining the example and we can start a
cookbook in the mpl docs.  If you would like to go this route, we can
add a section to the users guide for explained examples, aka a
cookbook.


Now that I think about it, maybe this example isn't suited for a  
cookbook. Or maybe I'm just being lazy and avoiding the work involved  
in writing an explanation. :P



I am curious though why you prefer to alter the default color cycle
rather than just passing the color in to the plot command -- it seems
more explicit to pass the color in directly rather than rely on the
default cycle.
JDH


Actually, I originally cycled through colors in my plot loop, which I  
agree is more explicit. However, I got tired of the extra code  
involved with this method and went looking for a way to change the  
defaults. Plus, I already have of a module of functions I use to  
change matplotlib defaults (different fontsizes, linewidths, etc. for  
publications, presentations, etc), and this function fit quite nicely  
with that module.


-Tony

PS. If it'd be useful to show different ways of cycling through  
colors, here's another version of my example:


#!/usr/bin/env python

This example defines the function ``cycle_cmap``, which changes the default
color cycle to use color intervals from a specified colormap.

The colormap settings are predefined for a few colormaps such that colors go
from light to dark and are restricted from being too light.

These settings are particularly useful for plotting lines that evolve in time,
where there is continuous gradient from light (early times) to dark (late
times).

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

REVERSE_CMAP = ['summer', 'autumn', 'winter', 'spring', 'copper']
CMAP_RANGE = dict(gray={'start':200, 'stop':0},
  Blues={'start':60, 'stop':255},
  Oranges={'start':60, 'stop':255},
  OrRd={'start':60, 'stop':255},
  BuGn={'start':60, 'stop':255},
  PuRd={'start':60, 'stop':255},
  YlGn={'start':60, 'stop':255},
  YlGnBu={'start':60, 'stop':255},
  YlOrBr={'start':60, 'stop':255},
  YlOrRd={'start':60, 'stop':255},
  hot={'start':230, 'stop':0},
  bone={'start':200, 'stop':0},
  pink={'start':160, 'stop':0})
 
def cmap_intervals(cmap='YlOrBr', length=50):
Return evenly spaced intervals of a given colormap `cmap`.

Colormaps listed in REVERSE_CMAP will be cycled in reverse order. Certain 
colormaps have pre-specified color ranges in CMAP_RANGE. These module 
variables ensure that colors cycle from light to dark and light colors are
not too close to white.

cmap - name of a matplotlib colormap (see matplotlib.pyplot.cm)
length - the number of colors used before cycling back to first color. When
`length` is large ( ~10), it is difficult to distinguish between
successive lines because successive colors are very similar.

cm = getattr(plt.cm, cmap)
if cmap in REVERSE_CMAP:
crange = dict(start=255, stop=0)
elif cmap in CMAP_RANGE:
crange = CMAP_RANGE[cmap]
else:
print '%s not in list of preset colormaps; may not be ideal' % cmap
crange = dict(start=0, stop=255)
if length  abs(crange['start'] - crange['stop']):
print ('Warning: the input length is greater than the number of' +
   'colors in the colormap; some colors will be repeated')
idx = np.linspace(crange['start'], crange['stop'], length).astype(np.int)
return cm(idx)

def cycle_cmap(cmap='YlOrBr', length=50):
Set default color cycle of matplotlib to a given colormap `cmap`.

The default color cycle of matplotlib is set to evenly distribute colors in 
color cycle over specified colormap.

Note: this function must be called before *any* plot commands because it
changes the default color cycle.

See ``cmap_intervals`` for input details.

color_cycle = cmap_intervals(cmap, length)
# set_default_color_cycle doesn't play nice with numpy arrays
mpl.axes.set_default_color_cycle(color_cycle.tolist())

if __name__ == '__main__':
numlines = 10
x = np.linspace(0, 10)
phase_shifts = np.linspace(0, np.pi, numlines)

# Change the default color cycle
cycle_cmap(length=numlines)
plt.subplot(311)
for shift in phase_shifts:
plt.plot(x, np.sin(x - shift), linewidth=2)

# Calculate a color cycle from a cmap and pass explicitly to plot
color_cycle = cmap_intervals('summer', 

[Matplotlib-users] Malloc error on show() with Wx/WxAgg

2009-05-27 Thread Tony S Yu
I'm running into a really bizarre error that seems to have started  
spontaneously (no changes I can think of were made to my system in the  
last few days and mpl was plotting without problems up until a few  
hours ago). When using WxAgg, the following code raises a malloc error.

  import matplotlib.pyplot as plt
  plt.plot([0, 1])
  plt.show()

Python(477,0xa0710720) malloc: *** error for object 0x220068: Non- 
aligned pointer being freed
*** set a breakpoint in malloc_error_break to debug

This error only occurs on the Wx/WxAgg backends AND when show() is  
called; Qt4Agg, TkAgg, and MacOSX backends work fine.

This error is also generated when starting ipython with the pylab flag  
(and WxAgg set as the default backend).

Sorry I can't give more information about the error itself; I'm not  
sure how to in this case.

Thanks in advance for your help,
-Tony

Mac OS X 10.5.7
Python 2.5.1
Matplotlib trunk r7142
WX 2.8.4.0 (mac-unicode)

--
Register Now for Creativity and Technology (CaT), June 3rd, NYC. CaT 
is a gathering of tech-side developers  brand creativity professionals. Meet
the minds behind Google Creative Lab, Visual Complexity, Processing,  
iPhoneDevCamp as they present alongside digital heavyweights like Barbarian 
Group, R/GA,  Big Spaceship. http://p.sf.net/sfu/creativitycat-com 
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Malloc error on show() with Wx/WxAgg

2009-05-27 Thread Tony S Yu
Correction, this error occurs on all GUI backends I've tried (I don't  
have gtk installed). The malloc error didn't occur on the other  
backends until I tried to interact with the plot window.

-T


On May 27, 2009, at 12:36 PM, Tony S Yu wrote:

 I'm running into a really bizarre error that seems to have started
 spontaneously (no changes I can think of were made to my system in the
 last few days and mpl was plotting without problems up until a few
 hours ago). When using WxAgg, the following code raises a malloc  
 error.

 import matplotlib.pyplot as plt
 plt.plot([0, 1])
 plt.show()

 Python(477,0xa0710720) malloc: *** error for object 0x220068: Non-
 aligned pointer being freed
 *** set a breakpoint in malloc_error_break to debug

 This error only occurs on the Wx/WxAgg backends AND when show() is
 called; Qt4Agg, TkAgg, and MacOSX backends work fine.

 This error is also generated when starting ipython with the pylab flag
 (and WxAgg set as the default backend).

 Sorry I can't give more information about the error itself; I'm not
 sure how to in this case.

 Thanks in advance for your help,
 -Tony

 Mac OS X 10.5.7
 Python 2.5.1
 Matplotlib trunk r7142
 WX 2.8.4.0 (mac-unicode)

 --
 Register Now for Creativity and Technology (CaT), June 3rd, NYC. CaT
 is a gathering of tech-side developers  brand creativity  
 professionals. Meet
 the minds behind Google Creative Lab, Visual Complexity, Processing, 
 iPhoneDevCamp as they present alongside digital heavyweights like  
 Barbarian
 Group, R/GA,  Big Spaceship. http://p.sf.net/sfu/creativitycat-com
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
Register Now for Creativity and Technology (CaT), June 3rd, NYC. CaT 
is a gathering of tech-side developers  brand creativity professionals. Meet
the minds behind Google Creative Lab, Visual Complexity, Processing,  
iPhoneDevCamp as they present alongside digital heavyweights like Barbarian 
Group, R/GA,  Big Spaceship. http://p.sf.net/sfu/creativitycat-com 
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] Error from ``python setupegg.py develop`` using trunk

2009-05-18 Thread Tony S Yu
Hi,

I run mpl from the svn trunk, but I ran into a problem today after  
pulling the newest version (my last update was probably a week ago).  
The full build output is copied below.

I build from trunk using the following commands:

$ python setup.py build_ext --inplace
$ python setupegg.py develop

and my build failed on setupegg.py. To be honest, I'm not sure what  
the second line even does, but in the past, I've run into problems  
without it.

Any help would be greatly appreciated.
-Tony

= 
= 
= 
= 

BUILDING MATPLOTLIB
 matplotlib: 0.98.6svn
 python: 2.5.1 (r251:54863, Feb  6 2009, 19:02:12)  [GCC
 4.0.1 (Apple Inc. build 5465)]
   platform: darwin

REQUIRED DEPENDENCIES
  numpy: 1.3.0
  freetype2: 9.16.3

OPTIONAL BACKEND DEPENDENCIES
 libpng: 1.2.29
Tkinter: Tkinter: 50704, Tk: 8.4, Tcl: 8.4
   wxPython: 2.8.4.0
 * WxAgg extension not required for wxPython  
 = 2.8
   Gtk+: no
 * Building for Gtk+ requires pygtk; you must  
be able
 * to import gtk in your build/install  
environment
Mac OS X native: yes
 Qt: no
Qt4: Qt: 4.4.0, PyQt4: 4.4.2
  Cairo: 1.4.12

OPTIONAL DATE/TIMEZONE DEPENDENCIES
   datetime: present, version unknown
   dateutil: matplotlib will provide
   pytz: 2008c

OPTIONAL USETEX DEPENDENCIES
 dvipng: 1.9
ghostscript: 8.57
  latex: 3.141592

[Edit setup.cfg to suppress the above messages]
= 
= 
= 
= 

pymods ['pylab']
packages ['matplotlib', 'matplotlib.backends',  
'matplotlib.projections', 'mpl_toolkits', 'mpl_toolkits.mplot3d',  
'mpl_toolkits.axes_grid', 'matplotlib.sphinxext',  
'matplotlib.numerix', 'matplotlib.numerix.mlab',  
'matplotlib.numerix.ma', 'matplotlib.numerix.linear_algebra',  
'matplotlib.numerix.random_array', 'matplotlib.numerix.fft',  
'matplotlib.delaunay', 'dateutil', 'dateutil/zoneinfo']
running develop
running egg_info
writing lib/matplotlib.egg-info/PKG-INFO
writing namespace_packages to lib/matplotlib.egg-info/ 
namespace_packages.txt
writing top-level names to lib/matplotlib.egg-info/top_level.txt
writing dependency_links to lib/matplotlib.egg-info/dependency_links.txt
reading manifest template 'MANIFEST.in'
warning: no files found matching 'MANIFEST'
warning: no files found matching 'lib/mpl_toolkits'
writing manifest file 'lib/matplotlib.egg-info/SOURCES.txt'
running build_ext
building 'matplotlib.ft2font' extension
Traceback (most recent call last):
   File setupegg.py, line 8, in module
 {'namespace_packages' : ['mpl_toolkits']}})
   File setup.py, line 267, in module
 **additional_params
   File /System/Library/Frameworks/Python.framework/Versions/2.5/lib/ 
python2.5/distutils/core.py, line 151, in setup
 dist.run_commands()
   File /System/Library/Frameworks/Python.framework/Versions/2.5/lib/ 
python2.5/distutils/dist.py, line 974, in run_commands
 self.run_command(cmd)
   File /System/Library/Frameworks/Python.framework/Versions/2.5/lib/ 
python2.5/distutils/dist.py, line 994, in run_command
 cmd_obj.run()
   File /System/Library/Frameworks/Python.framework/Versions/2.5/ 
Extras/lib/python/setuptools/command/develop.py, line 27, in run
 self.install_for_development()
   File /System/Library/Frameworks/Python.framework/Versions/2.5/ 
Extras/lib/python/setuptools/command/develop.py, line 88, in  
install_for_development
 self.run_command('build_ext')
   File /System/Library/Frameworks/Python.framework/Versions/2.5/lib/ 
python2.5/distutils/cmd.py, line 333, in run_command
 self.distribution.run_command(command)
   File /System/Library/Frameworks/Python.framework/Versions/2.5/lib/ 
python2.5/distutils/dist.py, line 994, in run_command
 cmd_obj.run()
   File /System/Library/Frameworks/Python.framework/Versions/2.5/ 
Extras/lib/python/setuptools/command/build_ext.py, line 46, in run
 _build_ext.run(self)
   File /System/Library/Frameworks/Python.framework/Versions/2.5/lib/ 
python2.5/distutils/command/build_ext.py, line 290, in run
 self.build_extensions()
   File /Library/Python/2.5/site-packages/Pyrex-0.9.8.5-py2.5.egg/ 
Pyrex/Distutils/build_ext.py, line 82, in build_extensions
 self.build_extension(ext)
   File /System/Library/Frameworks/Python.framework/Versions/2.5/ 
Extras/lib/python/setuptools/command/build_ext.py, line 175, in  
build_extension
 _build_ext.build_extension(self,ext)
   File /System/Library/Frameworks/Python.framework/Versions/2.5/lib/ 
python2.5/distutils/command/build_ext.py, line 453, in build_extension
 sources = self.swig_sources(sources, ext)
   File 

Re: [Matplotlib-users] Different plot settings for different circumstances ...

2009-04-21 Thread Tony S Yu

On Apr 21, 2009, at 1:49 PM, Chaitanya Krishna wrote:
 But, anyways the point of this mail is to ask if there is a clever way
 of making different plots for different circumstances. For example,
 trying to make a plot for publication in a journal demands it being
 made in one way while using it in a presentation demands you to make a
 different one and probably trying to use it in a report requires
 another one.

 So, is there a way to decouple the plot settings (like figure size,
 axes properties, tick properties, etc) from the data being plotted. If
 so, can someone give some examples.

Here's another example from the matplotlib docs that sounds more like  
what you're looking for:

http://matplotlib.sourceforge.net/examples/pylab_examples/customize_rc.html?highlight=set_pub

I use something similar to the ``set_pub`` method in the comments of  
the example. I have a module ``plotstyle`` which has methods for  
``presentation``, ``publication``, etc. and whenever I want a script  
to use a certain style I just add:

  import plotstyle
  plotstyle.presention()

Best,
-Tony

--
Stay on top of everything new and different, both inside and 
around Java (TM) technology - register by April 22, and save
$200 on the JavaOne (SM) conference, June 2-5, 2009, San Francisco.
300 plus technical and hands-on sessions. Register today. 
Use priority code J9JMT32. http://p.sf.net/sfu/p
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] only left and bottom border in figure frame

2009-02-06 Thread Tony S Yu


On Feb 6, 2009, at 8:45 AM, Zunbeltz Izaola wrote:


Dear all,

I would like to have a plot where the frame only have left and
bottom border. I can not find in the documentation any function to  
draw

the Rectangle contained in figure() only with this 2 lines. It is
possilbe?


Hi Zunbeltz,

Attached is an example of a custom Axes class that does what you want.  
There are examples at the bottom of the file that show its use. I  
worked on generalizing this idea for inclusion in MPL, but the code  
got really nasty, really quickly.


On a side note, if any of the MPL devs think this would make a useful  
API example (since this topic has come up a few times on the list),  
feel free to do whatever you want with it.


Cheers,
-Tony

#!/usr/bin/env python

Frame classes for customizing frame borders that surround the plot axes.

import numpy as np

import matplotlib.axes as maxes
import matplotlib.pyplot as plt
import matplotlib.artist as martist
import matplotlib.collections as col
import matplotlib.projections as projections


class Frame(martist.Artist):
Draw frame along the edges of the axes patch.

Frame position can be controlled upon initialization or by setting
`positions` property with a list of positions
['left', 'right', 'top', 'bottom' | 'all']

_position_list = ('left', 'right', 'top', 'bottom')
def __init__(self, axes, positions=('left', 'bottom'), **kwargs):

`positions` is a list of strings of frame positions to plot.
['left', 'right', 'top', 'bottom' | 'all']

super(Frame, self).__init__()
# TODO: allow more keyword configuration
self.axes = axes

rc = plt.rcParams
self.color = kwargs.pop('color', rc['axes.edgecolor'])
self.linewidth = kwargs.pop('linewidth', rc['axes.linewidth'])
self.linestyle = kwargs.pop('linestyle', 'solid')
self.positions = positions

def get_data(self):
Convenience method returns tuple of (x, y) data in `self.axes`
x, y = [], []
ax = self.axes
for artist in (ax.lines, ax.patches):
if not artist == []:
x.append(np.concatenate([a.get_xdata() for a in artist]))
y.append(np.concatenate([a.get_ydata() for a in artist]))
# TODO: get scatter data from ax.collections
return (np.concatenate(x), np.concatenate(y))

def _set_frame_position(self, positions):
Set positions where frame will be drawn.

`positions` is a list of strings of frame positions to plot.
['left', 'right', 'top', 'bottom' | 'all']

self._frame_on = self._frame_dict_from(positions)

def _get_frame_position(self):
return [p for p in self._position_list if self._frame_on[p]]

# xposition tuples turn on frame for (bottom, top)
_xposition_pairs = {(True, False): 'bottom', (False, True): 'top',
(True, True): 'both', (False, False): 'none'}
def _get_xposition(self, frame_on=None):
Returns position that matches `XAxis.set_ticks_position` inputs.

`frame_on` is a dict that matches frame positions with bools.

if frame_on is None:
frame_on = self._frame_on
return self._xposition_pairs[(frame_on['bottom'], frame_on['top'])]

# yposition tuples turn on frame for (left, right)
_yposition_pairs = {(True, False): 'left', (False, True): 'right',
(True, True): 'both', (False, False): 'none'}
def _get_yposition(self, frame_on=None):
Returns position that matches `YAxis.set_ticks_position` inputs.

`frame_on` is a dict that matches frame positions with bools.

if frame_on is None:
frame_on = self._frame_on
return self._yposition_pairs[(frame_on['left'], frame_on['right'])]

def _frame_dict_from(self, positions):
Parse `positions` and return xposition, yposition tuple

`positions` is a list of strings of frame positions to plot.
['left', 'right', 'top', 'bottom' | 'all']

frame_dict = dict.fromkeys(self._position_list, False)

if 'all' in positions:
frame_dict = dict.fromkeys(self._position_list, True)
else:
for position in positions:
frame_dict[position] = True
return frame_dict

def _set_ticks(self):
Overide this method to customize tick positioning.
# Draw ticks on axes only where a frame is drawn
self.axes.xaxis.set_ticks_position(self._get_xposition())
self.axes.yaxis.set_ticks_position(self._get_yposition())

_frame_lines = dict(bottom=[(0., 0.), (1., 0.)], top=[(0., 1.), (1., 1.)],
left=[(0., 0.), (0., 1.)], right=[(1., 0.), (1., 1.)])
def _make_frame(self):
Get axis frame specified by `self._frame_on`.
lines = [self._frame_lines[p] for p in 

[Matplotlib-users] GUI neutral animation example doesn't work with WxAgg/Wx

2008-10-23 Thread Tony S Yu
The GUI neutral animation example from the SciPy cookbook doesn't seem  
to work for Wx or WxAgg backends. A plot window opens but nothing  
happens. It appears to be some weird problem with ion on wx.

For example, the following code will run and immediately close:
  plt.ion()
  plt.plot(x, y)
  plt.show()
After removing plt.ion(), a plot window is opened and the program  
doesn't end until the window is closed (as expected).

If I use TkAgg or Qt4Agg (the only other GUI backends I have  
installed) the examples (above and below) work as expected.

-Tony

Full Example:
#
import matplotlib
matplotlib.use('WxAgg')
import matplotlib.pyplot as plt
import numpy as np

plt.ion()
x = np.arange(0, 2*np.pi, 0.01)
line, = plt.plot(x, np.sin(x))
for i in np.arange(1, 20):
 line.set_ydata(np.sin(x + i/10.0))
 plt.draw()
#

PS. This seems to work the same on both trunk and 0.98.3.

-
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK  win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100url=/
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] GUI neutral animation example doesn't work with WxAgg/Wx

2008-10-23 Thread Tony S Yu

On Oct 23, 2008, at 12:00 PM, John Hunter wrote:

 On Thu, Oct 23, 2008 at 10:30 AM, Tony S Yu [EMAIL PROTECTED] wrote:
 The GUI neutral animation example from the SciPy cookbook doesn't  
 seem
 to work for Wx or WxAgg backends. A plot window opens but nothing
 happens. It appears to be some weird problem with ion on wx.


 GUI neutral animation is not supported or recommended.  I need to
 update the cookbook, but if you want to do it that would be great as I
 am short on time until next week.

I'd be happy to help, but I'm not sure what had you in mind. Sorry I'm  
still a student---I need guidance. ;)

-Tony

-
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK  win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100url=/
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Polar plot

2008-09-17 Thread Tony S Yu

On Sep 17, 2008, at 1:59 AM, jan gillis wrote:

 Hello,

 I have a problem with polar plot, if i run the following code in
 matplotlib 0.98.3, polar plot is drawing a extra circle to go from
 angle -3.14159265 to angle 3.03753126. Is there a solution for this
 problem?

 
 import numpy as np
 from matplotlib.pyplot import figure, show, rc, grid

 # radar green, solid grid lines
 rc('grid', color='#316931', linewidth=1, linestyle='-')
 rc('xtick', labelsize=15)
 rc('ytick', labelsize=15)

 # force square figure and square axes looks better for polar, IMO
 fig = figure(figsize=(8,8))
 ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c')

 z = np.zeros((1,2000),complex)
 z.real = 0.2
 z.imag = np.arange(-50,50,0.05)
 gamma_r = np.transpose((z-1)/(z+1))

 ax.plot(np.angle(gamma_r), np.abs(gamma_r), '.-', zorder=0)

Hi Jan,

It looks like you get the circle because the angles you're plotting go  
from negative to positive radians in a weird way. The circle being  
drawn starts around 0 radians and goes clockwise by negative values.  
Then when it gets to - pi, it switches to positive indices, i.e. pi.  
Of course, these are the same points on a polar plot, but different  
angles, if you want to be consistent.

Here are a couple of quick solutions, but there but there maybe better  
ways of handling this.

# ~~
# get rid of the plot line above, and add the following
theta = np.angle(gamma_r)
mag = np.abs(gamma_r)

# option 1
ordered = np.argsort(theta, axis=0).squeeze()
ax.plot(theta[ordered], mag[ordered], '.-', zorder=0)

# option 2
neg_theta = np.where(theta  0)
theta[neg_theta] += 2 * np.pi
ax.plot(theta, mag, '.-', zorder=0)
# ~~

I hope that's helpful,
-Tony


 ax.set_rmax(2.0)
 grid(True)

 show()

 
 Kind regards,
 Jean

 -- 
 Jan Gillis
 Ghent University
 IMEC vzw - INTEC
 Sint-Pietersnieuwstraat 41
 B-9000 Gent
 Belgium
 tel. +32 9 264 33 33
 [EMAIL PROTECTED]


 -
 This SF.Net email is sponsored by the Moblin Your Move Developer's  
 challenge
 Build the coolest Linux based applications with Moblin SDK  win  
 great prizes
 Grand prize is a trip for two to an Open Source event anywhere in  
 the world
 http://moblin-contest.org/redirect.php?banner_id=100url=/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


-
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK  win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100url=/
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Buggy 2D plot with ylim and large y values

2008-09-02 Thread Tony S Yu

On Sep 2, 2008, at 6:56 PM, Fredrik Johansson wrote:

 Hi,

 I've encountered what appears to be a bug in matplotlib-0.98.3
 (Windows XP, Python 2.5). The following plot of a function with poles
 displays garbage (large filled boxes instead of a curve). There's
 large variation in the y values, but not so large that this shouldn't
 be possible to plot correctly.

 Is this problem known? Is there a workaround?

 from pylab import *
 x = [-2.97, -2.94, -2.91, -2.88, -2.85, -2.82, -2.79, -2.76, -2.73,  
 -2.7,
 -2.67, -2.64, -2.61, -2.58, -2.55, -2.52, -2.49, -2.46, -2.43, -2.4,  
 -2.37,
 -2.34, -2.31, -2.28, -2.25, -2.22, -2.19, -2.16, -2.13, -2.1, -2.07,  
 -2.04,
 -2.01, -1.98, -1.95, -1.92, -1.89, -1.86, -1.83, -1.8, -1.77, -1.74,  
 -1.71,
 -1.68, -1.65, -1.62, -1.59, -1.56, -1.53, -1.5, -1.47, -1.44, -1.41,  
 -1.38,
 -1.35, -1.32, -1.29,-1.26, -1.23, -1.2, -1.17, -1.14, -1.11, -1.08,  
 -1.05,
 -1.02, -0.99, -0.96, -0.93, -0.9, -0.87, -0.84, -0.81, -0.78, -0.75,  
 -0.72,
 -0.69, -0.66, -0.63, -0.6, -0.57, -0.54, -0.51, -0.48, -0.45, -0.42,  
 -0.39,
 -0.36, -0.33, -0.3, -0.27, -0.24, -0.21, -0.18, -0.15, -0.12, -0.09,  
 -0.06,
 -0.03]
 y = [7.40742e+6, 462976.0, 91463.4, 28950.0, 11867.8, 5732.96,  
 3104.37,
 1830.03, 1153.53, 768.963, 538.805, 395.968, 305.58, 248.666, 214.668,
 197.843, 195.517, 207.33, 235.138, 283.525, 361.162, 483.641, 679.315,
 1001.79, 1558.46, 2581.22, 4621.92, 9171.58, 21022.7, 60014.1,  
 249909.0,
 2.34376e+6, 6.0e+8, 3.75e+7, 960013.0, 146498.0, 40995.2,  
 15633.9,7200.57,
 3768.46, 2164.71, 1336.34, 875.104, 603.287, 436.34, 331.148, 264.559,
 223.743, 201.613, 194.594, 201.594, 223.706, 264.503, 331.072,  
 436.244,
 603.172, 874.968, 1336.19, 2164.53, 3768.26, 7200.35, 15633.7,  
 40994.9,
 146498.0, 960013.0, 3.75e+7, 6.0e+8, 2.34376e+6, 249909.0, 60013.7,
 21022.2, 9171.01, 4621.3, 2580.56, 1557.75, 1001.03, 678.491, 482.753,
 360.205, 282.492, 234.022, 206.125, 194.213, 196.431, 213.137,  
 247.004,
 303.774, 394.002, 536.66, 766.62, 1150.97, 1827.22, 3101.28, 5729.56,
 11864.0, 28945.8, 91458.8, 462971.0, 7.40741e+6]
 plot(x, y)
 ylim([-40, 40])
 show()

I may be missing something here, but everything plots fine *if you  
remove the call to ylim*. Note that the minimum y value is 194.213. I  
wouldn't expect to see anything if none of the data is between y =  
-40 .. 40. Sorry if I'm overlooking something.

Best,
-Tony

 --
 Fredrik

 -
 This SF.Net email is sponsored by the Moblin Your Move Developer's  
 challenge
 Build the coolest Linux based applications with Moblin SDK  win  
 great prizes
 Grand prize is a trip for two to an Open Source event anywhere in  
 the world
 http://moblin-contest.org/redirect.php?banner_id=100url=/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


-
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK  win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100url=/
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Box Off on Axis

2008-07-15 Thread Tony S Yu


On Jul 15, 2008, at 6:17 PM, Andrea Gavana wrote:


Hi All,

   I am helping my girlfriend in doing some plots for her thesis (!).
Normally, matplotlib puts the graph in a box, left y axis, bottom x
axis, right y axis, top x axis. What she would like to do is to remove
the right y axis and the top x axis, akin the matlab command box off
(if I remember correctly), leaving just the 2 principal axis in the
plot.
I remember seeing something like that done with matplotlib, but
tonight my google-fu is really bad...
Is there a way to do what she is asking me to do? ;-)


Hi Andrea,

Here's a class I wrote (see attached) to draw custom frames for  
matplotlib. It defaults to the plot style you describe above. To use  
the frame class, try:


 import pyplot as plt
 from frame import FrameAxes

 plt.subplot(111, projection='frameaxes')

And then plot as you normally would. If you want an example, just run  
the file directly (instead of importing).


I'm playing around with a more flexible implementation where the axes  
can be placed arbitrarily (i.e. not just on the edges of the plot),  
but progress has been slow because of design considerations.


Best,

-Tony

PS: note this requires Matplotlib 0.98

#!/usr/bin/env python

Frame classes for customizing frame borders that surround the plot axes.

import numpy as np

import matplotlib.axes as maxes
import matplotlib.pyplot as plt
import matplotlib.artist as martist
import matplotlib.collections as col
import matplotlib.projections as projections


class Frame(martist.Artist):
Draw frame along the edges of the axes patch.

Frame position can be controlled upon initialization or by setting
`positions` property with a list of positions
['left', 'right', 'top', 'bottom' | 'all']

_position_list = ('left', 'right', 'top', 'bottom')
def __init__(self, axes, positions=('left', 'bottom'), **kwargs):

`positions` is a list of strings of frame positions to plot.
['left', 'right', 'top', 'bottom' | 'all']

super(Frame, self).__init__()
# TODO: allow more keyword configuration
self.axes = axes

rc = plt.rcParams
self.color = kwargs.pop('color', rc['axes.edgecolor'])
self.linewidth = kwargs.pop('linewidth', rc['axes.linewidth'])
self.linestyle = kwargs.pop('linestyle', 'solid')
self.positions = positions

def get_data(self):
Convenience method returns tuple of (x, y) data in `self.axes`
x, y = [], []
ax = self.axes
for artist in (ax.lines, ax.patches):
if not artist == []:
x.append(np.concatenate([a.get_xdata() for a in artist]))
y.append(np.concatenate([a.get_ydata() for a in artist]))
# TODO: get scatter data from ax.collections
return (np.concatenate(x), np.concatenate(y))

def _set_frame_position(self, positions):
Set positions where frame will be drawn.

`positions` is a list of strings of frame positions to plot.
['left', 'right', 'top', 'bottom' | 'all']

self._frame_on = self._frame_dict_from(positions)

def _get_frame_position(self):
return [p for p in self._position_list if self._frame_on[p]]

# xposition tuples turn on frame for (bottom, top)
_xposition_pairs = {(True, False): 'bottom', (False, True): 'top',
(True, True): 'both', (False, False): 'none'}
def _get_xposition(self, frame_on=None):
Returns position that matches `XAxis.set_ticks_position` inputs.

`frame_on` is a dict that matches frame positions with bools.

if frame_on is None:
frame_on = self._frame_on
return self._xposition_pairs[(frame_on['bottom'], frame_on['top'])]

# yposition tuples turn on frame for (left, right)
_yposition_pairs = {(True, False): 'left', (False, True): 'right',
(True, True): 'both', (False, False): 'none'}
def _get_yposition(self, frame_on=None):
Returns position that matches `YAxis.set_ticks_position` inputs.

`frame_on` is a dict that matches frame positions with bools.

if frame_on is None:
frame_on = self._frame_on
return self._yposition_pairs[(frame_on['left'], frame_on['right'])]

def _frame_dict_from(self, positions):
Parse `positions` and return xposition, yposition tuple

`positions` is a list of strings of frame positions to plot.
['left', 'right', 'top', 'bottom' | 'all']

frame_dict = dict.fromkeys(self._position_list, False)

if 'all' in positions:
frame_dict = dict.fromkeys(self._position_list, True)
else:
for position in positions:
frame_dict[position] = True
return frame_dict

def _set_ticks(self):
Overide this method to customize tick positioning.
# Draw 

Re: [Matplotlib-users] plotting with marker 'o' but not filled

2008-07-12 Thread Tony S Yu

On Jul 12, 2008, at 1:50 PM, Alan wrote:

 Hi List,

 I use Fink for Mac OSX, tiger 10.4.11.

 So with MPL 0.90.1, this script works fine:

 from matplotlib.pylab import *
 import matplotlib, numpy
 print matplotlib.__version, numpy.__version__
 att1 = {'color': 'black', 'markerfacecolor': 'red', 'markersize':
 80.0, 'markeredgewidth': 1.0, 'alpha': 1.0, 'marker': 's',
 'markeredgecolor': 'blue'}
 att2 = {'color': 'black', 'markerfacecolor': None, 'markersize': 8.0,
 'markeredgewidth': 1.0, 'alpha': 1.0, 'marker': 'o',
 'markeredgecolor': 'blue'}
 plot([0],[0], **att1)
 plot([0],[0], **att2)
 show()

 I got just a blue circle line (not filled) over a red square. However,
 trying the same script with updated MPL 0.91.3, I got:

 [snip]
  File /sw/lib/python2.5/site-packages/matplotlib/colors.py, line
 279, in to_rgb
raise ValueError('to_rgb: Invalid rgb arg %s\n%s' % (str(arg),  
 exc))
 ValueError: to_rgb: Invalid rgb arg None
 cannot convert argument to rgb sequence

 Bottom line, version 0.91.3 simply doesn't like 'markerfacecolor':
 None anymore.

Could you try setting 'markerfacecolor' to 'none' (Note that this is  
the string, not the keyword). I'm on version 0.98.2, but I think this  
worked when I was using 0.91.3. I'm not sure why this change was made,  
though.

Best,
-Tony



 So, is it a bug, or there's another way of getting a simple circle  
 not filled?

 Many thanks in advance,
 Alan
 -- 
 Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
 Department of Biochemistry, University of Cambridge.
 80 Tennis Court Road, Cambridge CB2 1GA, UK.
 http://www.bio.cam.ac.uk/~awd28

 -
 Sponsored by: SourceForge.net Community Choice Awards: VOTE NOW!
 Studies have shown that voting for your favorite open source project,
 along with a healthy diet, reduces your potential for chronic lameness
 and boredom. Vote Now at http://www.sourceforge.net/community/cca08
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


-
Sponsored by: SourceForge.net Community Choice Awards: VOTE NOW!
Studies have shown that voting for your favorite open source project,
along with a healthy diet, reduces your potential for chronic lameness
and boredom. Vote Now at http://www.sourceforge.net/community/cca08
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] converting data between axis [0, 1] and data coordinates [min data, max data]

2008-06-30 Thread Tony S Yu


On Jun 30, 2008, at 11:13 AM, Michael Droettboom wrote:
transScale is where all of the (optionally) logarithmic  
transformation takes place.  I'm surprised


 transDesired = self.transScale + self.transLimits

didn't work for going from data to a (0, 0) - (1, 1) bounding box.   
Can you provide a small, yet complete, example that illustrates the  
bug so I can look at it further?


I tried to put together a simple example showing my problem, but the  
example worked properly! Doh!


It turns out that my problem was specific to using a bounding box as  
an input to transform:


=
from numpy.random import rand
import matplotlib.pyplot as plt

ax = plt.subplot(111)
xy = rand(5,2)
ax.loglog(xy[:, 0], xy[:, 1], 'ro')

trans = ax.transScale + ax.transLimits
result = trans.transform(ax.dataLim)
=

The above command gives me:
TypeError: 'Bbox' object is unsubscriptable
(Note, if I call `plot` instead of `loglog` I don't have problems).  
The quick solution is to replace the last line with


 result = trans.transform(ax.dataLim._points)

I guess I was confused because the transform worked fine with `plot`.  
Is the TypeError above expected behavior?


Thanks for your help.
-Tony

-
Check out the new SourceForge.net Marketplace.
It's the best place to buy or sell services for
just about anything Open Source.
http://sourceforge.net/services/buy/index.php___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] dataLim and getting the data from `scatter` (bonus: an attempt at a Frame class)

2008-06-30 Thread Tony S Yu


On Jun 30, 2008, at 10:10 PM, John Hunter wrote:

I'd love for you to take the lead on this.  Given my (and other
developers) constraints on time, we'll have only limited time to help,
but hopefully we can give you some pointers when you get stuck.


I don't know if I'm the best person to be taking this on, but if no  
one else is interested, then I'd be happy to take a shot at it.





Current Limitations:

* the frame can only be placed on the borders of the axes (mainly  
because I

don't know how to move the tickers anywhere else).


Look at how the transforms are set in the axis.Axis class for the
tickers - the ticks and labels have blended transforms which blend
data coords and axes coords.


That reminds me: does it make more sense to have the frame as an  
attribute/child of each axis (just as ticks are attributes of each  
axis)? It seemed more appropriate to me, but I just used the `frame`  
in axes because it was already defined.



It would be extremely useful if
you could develop and extensible API for axis handling (so one could
incorporate some of these Tufte extensions and related ideas at the
*user* level even if they are not built in, though we'd probably
supply some by default or by example)


I didn't really expect the Tufte-style frames to be incorporated into  
the core; Incidentally, my initial goal was just to play around with  
these Tufte-style frames, not to write a Frame class.



Keep us posted!


Will do. Thanks for your comments.

-Tony-
Check out the new SourceForge.net Marketplace.
It's the best place to buy or sell services for
just about anything Open Source.
http://sourceforge.net/services/buy/index.php___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] dataLim and getting the data from `scatter` (bonus: an attempt at a Frame class)

2008-06-29 Thread Tony S Yu
Hi. A couple of questions about `scatter`:Q1The bounding box `axes.dataLim` increases in size when calling scatter(x, y) compared to plot(x, y) (for the same x, y data, of course). I think this change is due to the size of the markers being added to the data limits (not sure if this is true). Is there an easy way to get the same data limits I would have for a call to `plot`?Q2Is there a way to get the data from the axes of a scatter plot?Initially I thought I could get it with:>>> for collection in ax.collections:>>>   for path in collection._paths:>>> print path.verticesBut this seems to be the path that draws the scatter markers. Any ideas?Frame Class==Finally, if anyone is interested, I'm playing around with a Frame class for `axes.frame`. This class adds customizable axes frames similar to the topic of this thread:http://sourceforge.net/mailarchive/message.php?msg_id=87d57vjgye.fsf%40peds-pc311.bsd.uchicago.eduIn this older thread, the SAGE axes frames were criticized for not being flexible enough. I've tried to make this class as general as possible (within my ability:). As an example of the flexibility of this Frame class, I've added some Tufte-style frames similar to:http://hupp.org/adam/weblog/2007/09/03/etframes-applying-the-ideas-of-edward-tufte-to-matplotlib/To the developers on this thread: If there's anything I could do to make the attached Frame class more flexible (and more suitable for possible inclusion into MPL), I'd be happy to get some feedback.Current Limitations:* the frame can only be placed on the borders of the axes (mainly because I don't know how to move the tickers anywhere else).* RangeFrame only works with linear data (I'm not sure how to use the `axes.transScale`to properly transform the data)* RangeFrame and DashDotFrame don't work properly with `scatter` (because of the questions in this post).The frame class itself isn't too long, but I got a little carried away adding in extra crap.Sorry for the long, rambling email.;)-Tony#!/usr/bin/env python

Frame classes for customizing frame borders that surround the plot axes.

import numpy as np
from numpy.random import rand

import matplotlib.axes as maxes
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.artist as martist
import matplotlib.collections as col
import matplotlib.projections as projections


class Frame(martist.Artist):
Draw frame along the edges of the axes patch.

Frame position can be controlled upon initialization or by setting
`frame_position` property with a list of positions
['left', 'right', 'top', 'bottom' | 'all']

_position_list = ('left', 'right', 'top', 'bottom')
def __init__(self, axes, positions=('left', 'bottom'), **kwargs):

`positions` is a list of strings of frame positions to plot.
['left', 'right', 'top', 'bottom' | 'all']

super(Frame, self).__init__()
# TODO: allow more keyword configuration
self.axes = axes

rc = plt.rcParams
self.color = kwargs.pop('color', rc['axes.edgecolor'])
self.linewidth = kwargs.pop('linewidth', rc['axes.linewidth'])
self.linestyle = kwargs.pop('linestyle', 'solid')
self.frame_position = positions

def get_data(self):
Convenience method returns tuple of (x, y) data in `self.axes`
x, y = [], []
ax = self.axes
for artist in (ax.lines, ax.patches):
if not artist == []:
x.append(np.concatenate([a.get_xdata() for a in artist]))
y.append(np.concatenate([a.get_ydata() for a in artist]))
# TODO: get scatter data from ax.collections
return (np.concatenate(x), np.concatenate(y))

def _set_frame_position(self, positions):
Set positions where frame will be drawn.

`positions` is a list of strings of frame positions to plot.
['left', 'right', 'top', 'bottom' | 'all']

self._frame_on = self._frame_dict_from(positions)

def _get_frame_position(self):
return [p for p in self._position_list if self._frame_on[p]]

# xposition tuples turn on frame for (bottom, top)
_xposition_pairs = {(True, False): 'bottom', (False, True): 'top',
(True, True): 'both', (False, False): 'none'}
def _get_xposition(self, frame_on=None):
Returns position that matches `XAxis.set_ticks_position` inputs.

`frame_on` is a dict that matches frame positions with bools.

if frame_on is None:
frame_on = self._frame_on
return self._xposition_pairs[(frame_on['bottom'], frame_on['top'])]

# yposition tuples turn on frame for (left, right)
_yposition_pairs = {(True, False): 'left', (False, True): 'right',
(True, True): 'both', (False, False): 'none'}
def _get_yposition(self, frame_on=None):
Returns position that matches 

Re: [Matplotlib-users] Radar / Spider Chars

2008-06-25 Thread Tony S Yu
I was reading through the projections docs and decided to take a shot  
at creating a radar chart class. The layout of the labels and legend  
is really off, but other than that, this seems to work OK. I couldn't  
figure out a good way to initialize the number of axes/variables, so  
there's an ugly function wrapping around the class def.


Anyway, I hope this is useful to somebody:

#!/usr/bin/env python
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
from pylab import *

def radar_factory(num_vars, frame='polygon'):
Create a radar chart with `num_vars` axes.

# calculate evenly-spaced axis angles
theta = 2*pi * linspace(0, 1-1/float(num_vars), num_vars)
# rotate theta such that the first axis is at the top
theta += pi/2

def draw_poly_frame(self, x0, y0, r):
# TODO: should use transforms to convert (x, y) to (r, theta)
verts = [(r*cos(t) + x0, r*sin(t) + y0) for t in theta]
return Polygon(verts, closed=True)

def draw_circle_frame(self, x0, y0, r):
return Circle((x0, y0), r)

frame_dict = {'polygon': draw_poly_frame, 'circle': draw_circle_frame}
if frame not in frame_dict:
raise ValueError, 'unknown value for `frame`: %s' % frame

class RadarAxes(PolarAxes):
Class for creating a radar chart (a.k.a. a spider or star chart)

http://en.wikipedia.org/wiki/Radar_chart

name = 'radar'
# use 1 line segment to connect specified points
RESOLUTION = 1
# define draw_frame method
draw_frame = frame_dict[frame]

def fill(self, *args, **kwargs):
Override fill so that line is closed by default
closed = kwargs.pop('closed', True)
return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)

def plot(self, *args, **kwargs):
Override plot so that line is closed by default
lines = super(RadarAxes, self).plot(*args, **kwargs)
for line in lines:
self._close_line(line)

def _close_line(self, line):
x, y = line.get_data()
# FIXME: markers at x[0], y[0] get doubled-up
if x[0] != x[-1]:
x = concatenate((x, [x[0]]))
y = concatenate((y, [y[0]]))
line.set_data(x, y)

def set_varlabels(self, labels):
self.set_thetagrids(theta * 180/pi, labels)

def get_axes_patch(self):
x0, y0 = (0.5, 0.5)
r = 0.5
return self.draw_frame(x0, y0, r)
register_projection(RadarAxes)

return theta

if __name__ == '__main__':
N = 5

theta = radar_factory(N)
# theta = radar_factory(N, frame='circle')

ax = subplot(111, projection='radar')

labels = ['humor', 'sarcasm', 'news content', 'America', 'overall']
colbert   = [8, 9, 5, 9, 7]
dailyshow = [9, 6, 8, 3, 9]

# ax.plot(theta, dailyshow, 'b-o')
# ax.plot(theta, colbert, 'r-s')

ax.fill(theta, dailyshow, 'b')
ax.fill(theta, colbert, 'r')
for patch in ax.patches:
patch.set_alpha(0.5)

# FIXME: legend doesn't work when fill is called
# ax.legend(['The Daily Show', 'Colbert Report'])

ax.set_varlabels(labels)
# FIXME: rgrid lines don't appear; works if RESOLUTION is increased.
rgrids((2, 4, 6, 8, 10))

grid(True)
show()



-Tony

On Jun 20, 2008, at 12:16 AM, Curtis Jensen wrote:


No guarantees on when I'll have time, but I'll work on it.

Thanks for the info.

--
Curtis

On Thu, Jun 19, 2008 at 8:17 AM, John Hunter [EMAIL PROTECTED]  
wrote:
On Wed, Jun 18, 2008 at 2:43 PM, Curtis Jensen [EMAIL PROTECTED] 
 wrote:
Nice.  Thanks.  I had tried to do something similar, but kept  
getting

a curved line between each data point.
Also, I too got errors with a previous versions of matplotlib, but  
0.98 works.


If someone were willing to add Radar plots to the matplotlib
functionality, would this be wanted by the users or maintainers?


Yes, certainly.  You may want to take a look at the polar
implementation (can you inherit from it?) to reuse as much as
possible.  Michael has also written a short guide to developers
working with nonlinear projections

http://matplotlib.sourceforge.net/doc/html/devel/add_new_projection.html

JDH



-
Check out the new SourceForge.net Marketplace.
It's the best place to buy or sell services for
just about anything Open Source.
http://sourceforge.net/services/buy/index.php___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Radar / Spider Chars

2008-06-17 Thread Tony S Yu

On Jun 15, 2008, at 11:54 AM, Curtis Jensen wrote:

 There was recently a post on Radar/Spider plotting
 (http://sourceforge.net/mailarchive/message.php?msg_id=4845303A.9050204%40epcc.ed.ac.uk
  
 ).
 I too am interested in creating Radar plots with matplot.  Is there a
 simple way to do this?

Here's a hack to get part of what you want:

=
from matplotlib.projections.polar import PolarAxes
from pylab import *

# Create 6 points (plus 7th point that matches the first) with  
coordinates r, theta
N = 6
theta = 2 * pi * linspace(0, 1, N+1)
r = rand(N+1)
r[N] = r[0]

# HACK: force PolarAxes to use 1 line segment to connect specified  
points
PolarAxes.RESOLUTION = 1

ax = subplot(111, polar=True)
c = ax.plot(theta, r, 'r-o')
show()
=

I think this only works on matplotlib 0.98. I tried using rgrids and  
thetagrids to change the labels, but for some reason I was getting a  
TypeError when I called either of those functions.

-Tony

-
Check out the new SourceForge.net Marketplace.
It's the best place to buy or sell services for
just about anything Open Source.
http://sourceforge.net/services/buy/index.php
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Easy question: how to select specific subplot for second (or more) time

2008-06-10 Thread Tony S Yu
Wow, a question I can actually answer:

ax1 = subplot(211)
ax2 = subplot(212)
ax1.plot([1,2,3])
ax2.plot([4,3,2])
ax1.plot([3,2,1])

Best,
-Tony

On Jun 10, 2008, at 9:09 AM, Mark Bakker wrote:

 Hello list -

 I want to plot something in two subplots, then add something to the  
 first subplot.
 How do I select the first subplot after I have plotted on the second  
 subplot?

 For example:
 subplot(211)
 plot([1,2,3])
 subplot(212)
 plot([4,3,2])

 Now I want to add something to the first subplot.
 So I thought I could do subplot(211) again, but that destroys the  
 subplot.
 Any suggestions?

 Thanks, Mark
 -
 Check out the new SourceForge.net Marketplace.
 It's the best place to buy or sell services for
 just about anything Open Source.
 http://sourceforge.net/services/buy/index.php___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


-
Check out the new SourceForge.net Marketplace.
It's the best place to buy or sell services for
just about anything Open Source.
http://sourceforge.net/services/buy/index.php
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Easy question: how to select specific subplot for second (or more) time

2008-06-10 Thread Tony S Yu

Hey Mark,

Actually, recalling subplot(211) seems to work for me. Strange. You  
may want to try forcing the first plot to remain before drawing the  
second:


subplot(211)
plot([1,2,3])
hold(True)
subplot(212)
plot([4,3,2])
subplot(211)
plot([3,2,1])

-Tony

On Jun 10, 2008, at 9:29 AM, Mark Bakker wrote:


Thanks Tony -

I was hoping there was a plyab-ish command.
Like you can do Figure(1), Figure(2), and then reselect Figure(1) to  
get access to the first figure. No such command for subplot, I  
understand.


Cheers, Mark

On Tue, Jun 10, 2008 at 3:27 PM, Tony S Yu [EMAIL PROTECTED] wrote:
Wow, a question I can actually answer:

ax1 = subplot(211)
ax2 = subplot(212)
ax1.plot([1,2,3])
ax2.plot([4,3,2])
ax1.plot([3,2,1])

Best,
-Tony


On Jun 10, 2008, at 9:09 AM, Mark Bakker wrote:

Hello list -

I want to plot something in two subplots, then add something to the  
first subplot.
How do I select the first subplot after I have plotted on the second  
subplot?


For example:
subplot(211)
plot([1,2,3])
subplot(212)
plot([4,3,2])

Now I want to add something to the first subplot.
So I thought I could do subplot(211) again, but that destroys the  
subplot.

Any suggestions?

Thanks, Mark
-
Check out the new SourceForge.net Marketplace.
It's the best place to buy or sell services for
just about anything Open Source.
http://sourceforge.net/services/buy/index.php___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users




-
Check out the new SourceForge.net Marketplace.
It's the best place to buy or sell services for
just about anything Open Source.
http://sourceforge.net/services/buy/index.php___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users