Re: [Matplotlib-users] Some questions regarding pcolor(mesh)/nbagg/FuncAnimate

2015-04-16 Thread Ryan Nelson
Tom,

Thanks for the code. As it was given, I had to change `blit=True` in the
`FuncAnimation` call in order to get this to work in a regular Qt backend.
It did not work with the nbagg backend; however, if I used this code it
works fine:

%matplotlib nbagg

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animate

class Testing(object):
def __init__(self, ):
self.fig = plt.figure()
array = np.random.rand(4,5)
array = np.zeros((4,5))
self.pc = plt.pcolor(array, edgecolor='k', linewidth=1.)#,
animated=True)
self.pc.set_clim([0, 1])
self.points = [plt.scatter(np.random.rand(), np.random.rand())]#,
animated=True)]

def update(self, iter_num):
array = np.random.rand(4*5)
self.pc.set_array(array)
for point in self.points:
point.set_offsets([np.random.rand(), np.random.rand()])
#return (self.pc, ) + tuple(self.points)


test = Testing()
ani = animate.FuncAnimation(test.fig, test.update, interval=250,
blit=False, frames=50)
plt.show()

Also this code solves the problem I was having with several scatter points
being displayed upon multiple runs of the same code cell.

I wasn't familiar with the animated keyword, and it is not well
documented yet. Can you give me a quick explanation of what it is doing?

Ben: thanks for the hint about the _stop() method. I might look into that
for my example.

Thank you all for your assistance. Things are working pretty much as I need
now!

Ryan

On Sun, Apr 12, 2015 at 9:24 AM, Thomas Caswell tcasw...@gmail.com wrote:

 You can


 ```

 #import matplotlib

 #matplotlib.use('nbagg')

 #%matplotlib nbagg

 import numpy as np

 import matplotlib.pyplot as plt

 import matplotlib.animation as animate


 class Testing(object):

 def __init__(self, ):

 self.fig = plt.figure()

 array = np.random.rand(4,5)

 array = np.zeros((4,5))

 self.pc = plt.pcolor(array, edgecolor='k', linewidth=1.,
 animated=True)

 self.pc.set_clim([0, 1])

 self.points = [plt.scatter(np.random.rand(), np.random.rand(),
 animated=True)]


 def update(self, iter_num):

 array = np.random.rand(4*5)

 self.pc.set_array(array)

 for point in self.points:

 point.set_offsets([np.random.rand(), np.random.rand()])


 return (self.pc, ) + tuple(self.points)



 test = Testing()

 ani = animate.FuncAnimation(test.fig, test.update, interval=10,
 blit=False, frames=50)

 plt.show()

 ```

 note the addition of the `set_clim` line in the `__init__` method.


 You can also update the scatter artist in-place.  The other changes will
 make it a bit for performant if you use bliting (which does not work with
 nbagg currently)

 Sorry I missed that part of the question first time through.

 Tom

 On Sun, Apr 12, 2015, 08:31 Ryan Nelson rnelsonc...@gmail.com wrote:

 Tom,

 Thanks for the links. It does seem like fragments of my problem are
 addressed in each of those comments, so I guess I'll have to wait for a bit
 until those things get resolved. For now, I can just tell my students to
 restart the IPython kernel each time they run the animation, which isn't
 that hard. It's too bad that there isn't a 'stop' method now, but it's good
 to hear that it isn't a completely terrible idea.

 I do still need help with Question #3 from my original email, though,
 because it affects both the Qt and nbagg backends, and it is a bit of a
 show stopper. I can't quite understand why initializing a pcolor(mesh) with
 random numbers makes it possible to update the array in an animation, but
 if you use all zeros or ones, it seems to be immutable.

 Ryan

 On Sat, Apr 11, 2015 at 8:35 PM, Thomas Caswell tcasw...@gmail.com
 wrote:

 Ryan,

 I have not looked at your exact issue yet, but there seems to be some
 underlying issues with animation and nbagg which we have not tracked down
 yet. See:

 https://github.com/matplotlib/matplotlib/pull/4290
 https://github.com/matplotlib/matplotlib/issues/4287
 https://github.com/matplotlib/matplotlib/issues/4288

 Running until a given condition is an interesting idea, but I think that
 means the animation objects needs to have a public 'stop' method first!

 Tom

 On Fri, Apr 10, 2015 at 3:00 PM Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Good afternoon, all!

 I'm really digging the nbagg backend, and I'm trying to use it to make
 an animation. As the subject suggests, though, I'm having some issues with
 these features. I'm using Python 3.4, Matplotlib 1.4.3, and IPython 3.1.
 Below is a small code sample that emulates my system. The pcolor call can
 be substituted for pcolormesh, and I see the same behavior. (Sorry this is
 a bit long. I tried to break it up as best as possible.)

 #
 #import matplotlib
 #matplotlib.use('nbagg')
 #%matplotlib nbagg
 import numpy as np
 import matplotlib.pyplot as plt
 import matplotlib.animation as animate

 class

Re: [Matplotlib-users] weird matplotlib imread question for png

2015-04-16 Thread Ryan Nelson

 xnview says it is 128*128*8, but  print
 imread('python-gray.png').shape says (128, 128, 3), however I suppose
 it should be (128, 128)!

Not sure that this is true, but I guess that xnview is using the third
dimension here to refer to a number of bytes. In this case, it is two
bytes, one for the black/white level and the other for alpha level. When
you import this with imread, the png is converted into a Numpy array. The
default behavior in this case is to create an array which is 128*128*3
because the third dimmension is the (R,G,B) levels, which will all be equal
for a gray scale image. This behavior is probably intentional so that you
don't have to write different code to handle gray/color images.

For python-color.png, it is my fault. xnview says it is 128*128*32, so
 it has alpha channel. Hence imread().shape =(128, 128, 4) is right

If the third dimension from xnview is bytes, then yes, you are correct.

btw. imread return array which has value between 0 and 1 for PNG file.
 But for other picture format, the value is 0~255. The manual says
 matplotlib reads PNG only by it self, and other files via PIL.But I
 think it is better to make the returned array consistent.

That is most likely due to the way that PNG and e.g. older JPG are defined.
PNG defines each RGBA value using float32, while older JPG uses uint8.
Therefor, it would not make sense to change the dtype of the image on
import.

Hope that helps.
Ryan




On Thu, Apr 16, 2015 at 10:51 AM, oyster lepto.pyt...@gmail.com wrote:

 Firstly, thanks, Fabrice Silva

 I have checked my picture files again.

 For python-gray.png, now it is attacched here or can be downloaded
 from
 http://bbs.blendercn.org/data/attachment/forum/201504/16/222351w3952n3o9968m9a5.png
 .
 xnview says it is 128*128*8, but  print
 imread('python-gray.png').shape says (128, 128, 3), however I suppose
 it should be (128, 128)!

 For python-color.png, it is my fault. xnview says it is 128*128*32, so
 it has alpha channel. Hence imread().shape =(128, 128, 4) is right

 btw. imread return array which has value between 0 and 1 for PNG file.
 But for other picture format, the value is 0~255. The manual says
 matplotlib reads PNG only by it self, and other files via PIL.But I
 think it is better to make the returned array consistent.


 --
 BPM Camp - Free Virtual Workshop May 6th at 10am PDT/1PM EDT
 Develop your own process in accordance with the BPMN 2 standard
 Learn Process modeling best practices with Bonita BPM through live
 exercises
 http://www.bonitasoft.com/be-part-of-it/events/bpm-camp-virtual-
 event?utm_
 source=Sourceforge_BPM_Camp_5_6_15utm_medium=emailutm_campaign=VA_SF
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
BPM Camp - Free Virtual Workshop May 6th at 10am PDT/1PM EDT
Develop your own process in accordance with the BPMN 2 standard
Learn Process modeling best practices with Bonita BPM through live exercises
http://www.bonitasoft.com/be-part-of-it/events/bpm-camp-virtual- event?utm_
source=Sourceforge_BPM_Camp_5_6_15utm_medium=emailutm_campaign=VA_SF___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Some questions regarding pcolor(mesh)/nbagg/FuncAnimate

2015-04-16 Thread Ryan Nelson
Ben,

Sorry. I probably should have just dropped that entirely. In my code
sample, it is actually commented out because it breaks the animation with
the nbagg backend. It was in Tom's example, so I left it in because I
wanted to find out what it was doing.

Ryan

On Thu, Apr 16, 2015 at 9:30 AM, Benjamin Root ben.r...@ou.edu wrote:

 I just noticed your use of animated=True. I have had trouble using that
 in the past with the animation module. It is a leftover from the days
 before the animation module and isn't actually used by it, IIRC. Try not
 supplying that argument.

 On Thu, Apr 16, 2015 at 8:18 AM, Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Tom,

 Thanks for the code. As it was given, I had to change `blit=True` in the
 `FuncAnimation` call in order to get this to work in a regular Qt backend.
 It did not work with the nbagg backend; however, if I used this code it
 works fine:
 
 %matplotlib nbagg

 import numpy as np
 import matplotlib.pyplot as plt
 import matplotlib.animation as animate

 class Testing(object):
 def __init__(self, ):
 self.fig = plt.figure()
 array = np.random.rand(4,5)
 array = np.zeros((4,5))
 self.pc = plt.pcolor(array, edgecolor='k', linewidth=1.)#,
 animated=True)
 self.pc.set_clim([0, 1])
 self.points = [plt.scatter(np.random.rand(), np.random.rand())]#,
 animated=True)]

 def update(self, iter_num):
 array = np.random.rand(4*5)
 self.pc.set_array(array)
 for point in self.points:
 point.set_offsets([np.random.rand(), np.random.rand()])
 #return (self.pc, ) + tuple(self.points)


 test = Testing()
 ani = animate.FuncAnimation(test.fig, test.update, interval=250,
 blit=False, frames=50)
 plt.show()
 
 Also this code solves the problem I was having with several scatter
 points being displayed upon multiple runs of the same code cell.

 I wasn't familiar with the animated keyword, and it is not well
 documented yet. Can you give me a quick explanation of what it is doing?

 Ben: thanks for the hint about the _stop() method. I might look into that
 for my example.

 Thank you all for your assistance. Things are working pretty much as I
 need now!

 Ryan

 On Sun, Apr 12, 2015 at 9:24 AM, Thomas Caswell tcasw...@gmail.com
 wrote:

 You can


 ```

 #import matplotlib

 #matplotlib.use('nbagg')

 #%matplotlib nbagg

 import numpy as np

 import matplotlib.pyplot as plt

 import matplotlib.animation as animate


 class Testing(object):

 def __init__(self, ):

 self.fig = plt.figure()

 array = np.random.rand(4,5)

 array = np.zeros((4,5))

 self.pc = plt.pcolor(array, edgecolor='k', linewidth=1.,
 animated=True)

 self.pc.set_clim([0, 1])

 self.points = [plt.scatter(np.random.rand(), np.random.rand(),
 animated=True)]


 def update(self, iter_num):

 array = np.random.rand(4*5)

 self.pc.set_array(array)

 for point in self.points:

 point.set_offsets([np.random.rand(), np.random.rand()])


 return (self.pc, ) + tuple(self.points)



 test = Testing()

 ani = animate.FuncAnimation(test.fig, test.update, interval=10,
 blit=False, frames=50)

 plt.show()

 ```

 note the addition of the `set_clim` line in the `__init__` method.


 You can also update the scatter artist in-place.  The other changes will
 make it a bit for performant if you use bliting (which does not work with
 nbagg currently)

 Sorry I missed that part of the question first time through.

 Tom

 On Sun, Apr 12, 2015, 08:31 Ryan Nelson rnelsonc...@gmail.com wrote:

 Tom,

 Thanks for the links. It does seem like fragments of my problem are
 addressed in each of those comments, so I guess I'll have to wait for a bit
 until those things get resolved. For now, I can just tell my students to
 restart the IPython kernel each time they run the animation, which isn't
 that hard. It's too bad that there isn't a 'stop' method now, but it's good
 to hear that it isn't a completely terrible idea.

 I do still need help with Question #3 from my original email, though,
 because it affects both the Qt and nbagg backends, and it is a bit of a
 show stopper. I can't quite understand why initializing a pcolor(mesh) with
 random numbers makes it possible to update the array in an animation, but
 if you use all zeros or ones, it seems to be immutable.

 Ryan

 On Sat, Apr 11, 2015 at 8:35 PM, Thomas Caswell tcasw...@gmail.com
 wrote:

 Ryan,

 I have not looked at your exact issue yet, but there seems to be some
 underlying issues with animation and nbagg which we have not tracked down
 yet. See:

 https://github.com/matplotlib/matplotlib/pull/4290
 https://github.com/matplotlib/matplotlib/issues/4287
 https://github.com/matplotlib/matplotlib/issues/4288

 Running until a given condition is an interesting idea, but I think
 that means the animation objects needs to have a public 'stop' method 
 first!

 Tom

 On Fri, Apr 10

Re: [Matplotlib-users] weird matplotlib imread question for png

2015-04-16 Thread Ryan Nelson
Oops. I meant bits not bytes in my earlier statements. Sorry.

On Thu, Apr 16, 2015 at 11:24 AM, Ryan Nelson rnelsonc...@gmail.com wrote:

 xnview says it is 128*128*8, but  print
 imread('python-gray.png').shape says (128, 128, 3), however I suppose
 it should be (128, 128)!

 Not sure that this is true, but I guess that xnview is using the third
 dimension here to refer to a number of bytes. In this case, it is two
 bytes, one for the black/white level and the other for alpha level. When
 you import this with imread, the png is converted into a Numpy array. The
 default behavior in this case is to create an array which is 128*128*3
 because the third dimmension is the (R,G,B) levels, which will all be equal
 for a gray scale image. This behavior is probably intentional so that you
 don't have to write different code to handle gray/color images.

 For python-color.png, it is my fault. xnview says it is 128*128*32, so
 it has alpha channel. Hence imread().shape =(128, 128, 4) is right

 If the third dimension from xnview is bytes, then yes, you are correct.

 btw. imread return array which has value between 0 and 1 for PNG file.
 But for other picture format, the value is 0~255. The manual says
 matplotlib reads PNG only by it self, and other files via PIL.But I
 think it is better to make the returned array consistent.

 That is most likely due to the way that PNG and e.g. older JPG are
 defined. PNG defines each RGBA value using float32, while older JPG uses
 uint8. Therefor, it would not make sense to change the dtype of the image
 on import.

 Hope that helps.
 Ryan




 On Thu, Apr 16, 2015 at 10:51 AM, oyster lepto.pyt...@gmail.com wrote:

 Firstly, thanks, Fabrice Silva

 I have checked my picture files again.

 For python-gray.png, now it is attacched here or can be downloaded
 from
 http://bbs.blendercn.org/data/attachment/forum/201504/16/222351w3952n3o9968m9a5.png
 .
 xnview says it is 128*128*8, but  print
 imread('python-gray.png').shape says (128, 128, 3), however I suppose
 it should be (128, 128)!

 For python-color.png, it is my fault. xnview says it is 128*128*32, so
 it has alpha channel. Hence imread().shape =(128, 128, 4) is right

 btw. imread return array which has value between 0 and 1 for PNG file.
 But for other picture format, the value is 0~255. The manual says
 matplotlib reads PNG only by it self, and other files via PIL.But I
 think it is better to make the returned array consistent.


 --
 BPM Camp - Free Virtual Workshop May 6th at 10am PDT/1PM EDT
 Develop your own process in accordance with the BPMN 2 standard
 Learn Process modeling best practices with Bonita BPM through live
 exercises
 http://www.bonitasoft.com/be-part-of-it/events/bpm-camp-virtual-
 event?utm_
 source=Sourceforge_BPM_Camp_5_6_15utm_medium=emailutm_campaign=VA_SF
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users



--
BPM Camp - Free Virtual Workshop May 6th at 10am PDT/1PM EDT
Develop your own process in accordance with the BPMN 2 standard
Learn Process modeling best practices with Bonita BPM through live exercises
http://www.bonitasoft.com/be-part-of-it/events/bpm-camp-virtual- event?utm_
source=Sourceforge_BPM_Camp_5_6_15utm_medium=emailutm_campaign=VA_SF___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Some questions regarding pcolor(mesh)/nbagg/FuncAnimate

2015-04-12 Thread Ryan Nelson
Tom,

Thanks for the links. It does seem like fragments of my problem are
addressed in each of those comments, so I guess I'll have to wait for a bit
until those things get resolved. For now, I can just tell my students to
restart the IPython kernel each time they run the animation, which isn't
that hard. It's too bad that there isn't a 'stop' method now, but it's good
to hear that it isn't a completely terrible idea.

I do still need help with Question #3 from my original email, though,
because it affects both the Qt and nbagg backends, and it is a bit of a
show stopper. I can't quite understand why initializing a pcolor(mesh) with
random numbers makes it possible to update the array in an animation, but
if you use all zeros or ones, it seems to be immutable.

Ryan

On Sat, Apr 11, 2015 at 8:35 PM, Thomas Caswell tcasw...@gmail.com wrote:

 Ryan,

 I have not looked at your exact issue yet, but there seems to be some
 underlying issues with animation and nbagg which we have not tracked down
 yet. See:

 https://github.com/matplotlib/matplotlib/pull/4290
 https://github.com/matplotlib/matplotlib/issues/4287
 https://github.com/matplotlib/matplotlib/issues/4288

 Running until a given condition is an interesting idea, but I think that
 means the animation objects needs to have a public 'stop' method first!

 Tom

 On Fri, Apr 10, 2015 at 3:00 PM Ryan Nelson rnelsonc...@gmail.com wrote:

 Good afternoon, all!

 I'm really digging the nbagg backend, and I'm trying to use it to make an
 animation. As the subject suggests, though, I'm having some issues with
 these features. I'm using Python 3.4, Matplotlib 1.4.3, and IPython 3.1.
 Below is a small code sample that emulates my system. The pcolor call can
 be substituted for pcolormesh, and I see the same behavior. (Sorry this is
 a bit long. I tried to break it up as best as possible.)

 #
 #import matplotlib
 #matplotlib.use('nbagg')
 #%matplotlib nbagg
 import numpy as np
 import matplotlib.pyplot as plt
 import matplotlib.animation as animate

 class Testing(object):
 def __init__(self, ):
 self.fig = plt.figure()
 array = np.random.rand(4,5)
 #array = np.zeros((4,5))
 self.pc = plt.pcolor(array, edgecolor='k', linewidth=1.)
 self.points = [plt.scatter(np.random.rand(), np.random.rand())]

 def update(self, iter_num):
 array = np.random.rand(4*5)
 self.pc.set_array(array)
 for point in self.points:
 point.remove()
 self.points = [plt.scatter(np.random.rand(), np.random.rand())]

 test = Testing()
 animate.FuncAnimation(test.fig, test.update, interval=1000, blit=False)
 plt.show()
 ###

 1. As is, this code runs fine with a Qt backend. It also runs fine as a
 first call in a notebook if the `show` call is commented out and the
 `%matplotlib` line is uncommented. However, if the `show` call is left in
 and the `matplotlib.use` call is uncommented, then the pcolor array
 changes, but the scatterpoint only shows on the first update and then
 disappears forever. What is the difference between these two invocations?

 2. With the `%matplotlib` magic uncommented and `show` removed, the first
 invocation of this as a cell works fine. Closing the figure (with the red
 X) and running the cell again shows two scatter plot points. Running it a
 third time shows three scatter plot points. If you call `plt.clf` in the
 next cell, I get a series of errors as follows:
 _
 ERROR:tornado.application:Exception in callback bound method
 TimerTornado._on_timer of matplotlib.backends.backend_nbagg.TimerTornado
 object at 0x7f894cb10f98
 Traceback (most recent call last):
   File /usr/lib64/python3.4/site-packages/tornado/ioloop.py, line 976,
 in _run
 return self.callback()
   File /usr/lib64/python3.4/site-packages/matplotlib/backend_bases.py,
 line 1290, in _on_timer
 ret = func(*args, **kwargs)
   File /usr/lib64/python3.4/site-packages/matplotlib/animation.py, line
 925, in _step
 still_going = Animation._step(self, *args)
   File /usr/lib64/python3.4/site-packages/matplotlib/animation.py, line
 784, in _step
 self._draw_next_frame(framedata, self._blit)
   File /usr/lib64/python3.4/site-packages/matplotlib/animation.py, line
 803, in _draw_next_frame
 self._draw_frame(framedata)
   File /usr/lib64/python3.4/site-packages/matplotlib/animation.py, line
 1106, in _draw_frame
 self._drawn_artists = self._func(framedata, *self._args)
   File ipython-input-2-f9290d8f6154, line 22, in update
 point.remove()
   File /usr/lib64/python3.4/site-packages/matplotlib/artist.py, line
 139, in remove
 self._remove_method(self)
   File /usr/lib64/python3.4/site-packages/matplotlib/axes/_base.py,
 line 1479, in lambda
 collection._remove_method = lambda h: self.collections.remove(h)
 ValueError: list.remove(x): x not in list
 __
 Why does this happen? Is there a way to close the animation cleanly?

 3. If I uncomment the `np.zeros

Re: [Matplotlib-users] Set a 3-D point?

2015-03-29 Thread Ryan Nelson
Prahas,

You're example is a little strange because when I set `x0 = (-1,0,0.5)`,
your function works fine on Python 2. Are you trying to set t0?

Note, your function does not compile on Python 3. You should try to be more
explicit with that first argument in that function. For example, does the
following do what you expect:
-
# I changed the equation -- it's not Lorenz.
import numpy as np
N_trajectories = 5

def lorentz_deriv(xyz, t0, aa=1.1, yy=0.87):
Compute the time-derivative of a Lorentz system.
x, y, z = xyz[0], xyz[1], xyz[2]
vals =  [y*(z-1+x*x)+yy*x, x*(3*z+1-x*x)+yy*y, -2*z*(aa+x*y)]
return np.array(vals)

# Choose random starting points, uniformly distributed from -15 to 15

np.random.seed(1)

# Here's the statement which assigns the initial conditions:

x0 = -15 + 30 * np.random.random((3, N_trajectories))
#x0 = (-1, 0, 1.5)
lorentz_deriv(x0, 1.)


This gives me an answer for both Python2 and Python3 with both values of
x0. Is that what you want?

Ryan



On Sun, Mar 29, 2015 at 1:07 PM, Prahas David Nafissian 
prahas.mu...@gmail.com wrote:


 Hi Mat-Plotters,

 I'm trying to modify the below code so that I can
 set the initial conditions to (-1,0,0.5).

 The code below randomly sets the initial conditions:

 **

 # I changed the equation -- it's not Lorenz.

 N_trajectories = 1

 def lorentz_deriv((x, y, z), t0, aa=1.1, yy=0.87):
 Compute the time-derivative of a Lorentz system.
 return [y*(z-1+x*x)+yy*x, x*(3*z+1-x*x)+yy*y, -2*z*(aa+x*y)]

 # Choose random starting points, uniformly distributed from -15 to 15

 np.random.seed(1)

 *# Here's the statement which assigns the initial conditions:*

 x0 = -15 + 30 * np.random.random((N_trajectories, 3))

 **

 I tried simply doing this:

 x0 = (-1,0,0.5)

 but I get this error:

 ValueError: need more than 1 value to unpack


 What am I missing?  What is the correct way to make the assignment?


 Thanks!


 --Prahas






 --
 Dive into the World of Parallel Programming The Go Parallel Website,
 sponsored
 by Intel and developed in partnership with Slashdot Media, is your hub for
 all
 things parallel software development, from weekly thought leadership blogs
 to
 news, videos, case studies, tutorials and more. Take a look and join the
 conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Best way to display image from URL in Python3

2015-03-20 Thread Ryan Nelson
For me, if I change the script from the PR to what is shown below,
everything works fine in both Python 2.7 and 3.4 (Anaconda environments,
everything updated):
##
url = 'http://www.libpng.org/pub/png/img_png/pngnow.png'
try:
import urllib2
data = urllib2.urlopen(url)
except Exception:
import urllib.request
from io import BytesIO
data = BytesIO(urllib.request.urlopen(url).read())

from matplotlib import pyplot

image = pyplot.imread(data)  # crash on py3.x
pyplot.imshow(image)
pyplot.show()
#
But as you can see, the Python 3 version requires the addition of BytesIO
and read(). I take it that this is not supposed to be the case.

Ryan

On Fri, Mar 20, 2015 at 11:48 AM, Ryan Nelson rnelsonc...@gmail.com wrote:

 Thanks, Ben. I should have made that more clear. If I run the code from
 the PR, I get the following error:

 Traceback (most recent call last):
   File junk.py, line 11, in module
 image = pyplot.imread(data)  # crash on py3.x
   File
 /home/nelson/apps/miniconda/lib/python3.4/site-packages/matplotlib/pyplot.py,
 line 2215, in imread
 return _imread(*args, **kwargs)
   File
 /home/nelson/apps/miniconda/lib/python3.4/site-packages/matplotlib/image.py,
 line 1270, in imread
 return handler(fname)
 RuntimeError: _image_module::readpng: file not recognized as a PNG file

 My code that I'm trying to port essentially does the same thing, and I get
 the same error. I ran this example just now from Anaconda Python 3.4
 install with MPL 1.4.3.

 My impression from the PR was that this should work out of the box now. I
 figured that maybe that was not quite the case. The implementations between
 Py2 and 3 are quite different. Figured there must be a different way that I
 wasn't aware of.

 Ryan

 On Fri, Mar 20, 2015 at 9:51 AM, Benjamin Root ben.r...@ou.edu wrote:

 According to the PR you reference, the fix for this was merged back in
 Jan 2013, so that means that this fix is in version 1.2.x and up. Are you
 saying that you still can't do imread(urllib.request.urlopen(url))?

 On Thu, Mar 19, 2015 at 8:54 PM, Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Hello all,

 I'm porting over some code that used Py2.7 urllib2.urlopen(url) to grab
 some image data from the net and load with pyplot.imread. It doesn't work
 quite right in Py3.4. I found a couple of refs:

 https://github.com/matplotlib/matplotlib/pull/1650

 http://stackoverflow.com/questions/15183170/python-crash-when-downloading-image-as-numpy-array

 They suggest io.BytesIO(urllib.request.urlopen(url).read()) as a
 replacement for Py3. Is this the best practice? Does anyone know a simpler
 way to do this?

 Ryan


 --
 Dive into the World of Parallel Programming The Go Parallel Website,
 sponsored
 by Intel and developed in partnership with Slashdot Media, is your hub
 for all
 things parallel software development, from weekly thought leadership
 blogs to
 news, videos, case studies, tutorials and more. Take a look and join the
 conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users




--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Best way to display image from URL in Python3

2015-03-20 Thread Ryan Nelson
Thanks, Ben. I should have made that more clear. If I run the code from the
PR, I get the following error:

Traceback (most recent call last):
  File junk.py, line 11, in module
image = pyplot.imread(data)  # crash on py3.x
  File
/home/nelson/apps/miniconda/lib/python3.4/site-packages/matplotlib/pyplot.py,
line 2215, in imread
return _imread(*args, **kwargs)
  File
/home/nelson/apps/miniconda/lib/python3.4/site-packages/matplotlib/image.py,
line 1270, in imread
return handler(fname)
RuntimeError: _image_module::readpng: file not recognized as a PNG file

My code that I'm trying to port essentially does the same thing, and I get
the same error. I ran this example just now from Anaconda Python 3.4
install with MPL 1.4.3.

My impression from the PR was that this should work out of the box now. I
figured that maybe that was not quite the case. The implementations between
Py2 and 3 are quite different. Figured there must be a different way that I
wasn't aware of.

Ryan

On Fri, Mar 20, 2015 at 9:51 AM, Benjamin Root ben.r...@ou.edu wrote:

 According to the PR you reference, the fix for this was merged back in Jan
 2013, so that means that this fix is in version 1.2.x and up. Are you
 saying that you still can't do imread(urllib.request.urlopen(url))?

 On Thu, Mar 19, 2015 at 8:54 PM, Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Hello all,

 I'm porting over some code that used Py2.7 urllib2.urlopen(url) to grab
 some image data from the net and load with pyplot.imread. It doesn't work
 quite right in Py3.4. I found a couple of refs:

 https://github.com/matplotlib/matplotlib/pull/1650

 http://stackoverflow.com/questions/15183170/python-crash-when-downloading-image-as-numpy-array

 They suggest io.BytesIO(urllib.request.urlopen(url).read()) as a
 replacement for Py3. Is this the best practice? Does anyone know a simpler
 way to do this?

 Ryan


 --
 Dive into the World of Parallel Programming The Go Parallel Website,
 sponsored
 by Intel and developed in partnership with Slashdot Media, is your hub
 for all
 things parallel software development, from weekly thought leadership
 blogs to
 news, videos, case studies, tutorials and more. Take a look and join the
 conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users



--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Best way to display image from URL in Python3

2015-03-20 Thread Ryan Nelson
I can understand that switching from Py 2 to 3 is going to require a change
from urllib2.urlopen to urllib.requests.urlopen, but the addition of
BytesIO and read() makes the transition tricky. It was not obvious to me
why that wouldn't work right off the bat, which is why I had to dig up that
PR and SO post.

As an alternate question, then: would a PR be welcome that makes it so that
URL info can be passed directly to the imread function? There's already a
test to see if fname is a string. Maybe a quick check to see if it starts
with http. Then imread could handle all of this business internally.

Thanks

Ryan


On Fri, Mar 20, 2015 at 12:24 PM, Thomas Caswell tcasw...@gmail.com wrote:

 I think `six` (which we use to smooth over the 2/3 changes) has a way of
 dealing with atleast the urllib renaming .

 On Fri, Mar 20, 2015 at 11:58 AM Ryan Nelson rnelsonc...@gmail.com
 wrote:

 For me, if I change the script from the PR to what is shown below,
 everything works fine in both Python 2.7 and 3.4 (Anaconda environments,
 everything updated):
 ##
 url = 'http://www.libpng.org/pub/png/img_png/pngnow.png'
 try:
 import urllib2
 data = urllib2.urlopen(url)
 except Exception:
 import urllib.request
 from io import BytesIO
 data = BytesIO(urllib.request.urlopen(url).read())

 from matplotlib import pyplot

 image = pyplot.imread(data)  # crash on py3.x
 pyplot.imshow(image)
 pyplot.show()
 #
 But as you can see, the Python 3 version requires the addition of BytesIO
 and read(). I take it that this is not supposed to be the case.

 Ryan

 On Fri, Mar 20, 2015 at 11:48 AM, Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Thanks, Ben. I should have made that more clear. If I run the code from
 the PR, I get the following error:

 Traceback (most recent call last):
   File junk.py, line 11, in module
 image = pyplot.imread(data)  # crash on py3.x
   File
 /home/nelson/apps/miniconda/lib/python3.4/site-packages/matplotlib/pyplot.py,
 line 2215, in imread
 return _imread(*args, **kwargs)
   File
 /home/nelson/apps/miniconda/lib/python3.4/site-packages/matplotlib/image.py,
 line 1270, in imread
 return handler(fname)
 RuntimeError: _image_module::readpng: file not recognized as a PNG file

 My code that I'm trying to port essentially does the same thing, and I
 get the same error. I ran this example just now from Anaconda Python 3.4
 install with MPL 1.4.3.

 My impression from the PR was that this should work out of the box now.
 I figured that maybe that was not quite the case. The implementations
 between Py2 and 3 are quite different. Figured there must be a different
 way that I wasn't aware of.

 Ryan

 On Fri, Mar 20, 2015 at 9:51 AM, Benjamin Root ben.r...@ou.edu wrote:

 According to the PR you reference, the fix for this was merged back in
 Jan 2013, so that means that this fix is in version 1.2.x and up. Are you
 saying that you still can't do imread(urllib.request.urlopen(url))?

 On Thu, Mar 19, 2015 at 8:54 PM, Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Hello all,

 I'm porting over some code that used Py2.7 urllib2.urlopen(url) to
 grab some image data from the net and load with pyplot.imread. It doesn't
 work quite right in Py3.4. I found a couple of refs:

 https://github.com/matplotlib/matplotlib/pull/1650

 http://stackoverflow.com/questions/15183170/python-crash-when-downloading-image-as-numpy-array

 They suggest io.BytesIO(urllib.request.urlopen(url).read()) as a
 replacement for Py3. Is this the best practice? Does anyone know a simpler
 way to do this?

 Ryan


 --
 Dive into the World of Parallel Programming The Go Parallel Website,
 sponsored
 by Intel and developed in partnership with Slashdot Media, is your hub
 for all
 things parallel software development, from weekly thought leadership
 blogs to
 news, videos, case studies, tutorials and more. Take a look and join
 the
 conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users




 
 --
 Dive into the World of Parallel Programming The Go Parallel Website,
 sponsored
 by Intel and developed in partnership with Slashdot Media, is your hub
 for all
 things parallel software development, from weekly thought leadership
 blogs to
 news, videos, case studies, tutorials and more. Take a look and join the
 conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
Dive into the World of Parallel Programming

Re: [Matplotlib-users] Best way to display image from URL in Python3

2015-03-20 Thread Ryan Nelson
A little update. It seems that this seems to be specific to Linux in some
way. I tried the original script from the PR under a couple of conditions:
* on Windows 7 Anaconda Python 2.7 and 3.4 -- everything works both versions
* on Anaconda Python 2.7 and 3.4 Linux version -- only the 2.7 version works
* on Gentoo Linux Python 2.7 and 3.4, MPL 1.4.3 -- only the 2.7 version
works
Hope that helps.

Ryan

On Fri, Mar 20, 2015 at 3:41 PM, Jerzy Karczmarczuk 
jerzy.karczmarc...@unicaen.fr wrote:


 Le 20/03/2015 16:57, Ryan Nelson a écrit :
  For me, if I change the script from the PR to what is shown below,
  everything works fine in both Python 2.7 and 3.4 (Anaconda
  environments, everything updated):
  ##
  url = 'http://www.libpng.org/pub/png/img_png/pngnow.png'
  try:
  import urllib2
  data = urllib2.urlopen(url)
  except Exception:
  import urllib.request
  from io import BytesIO
  data = BytesIO(urllib.request.urlopen(url).read())
 
  from matplotlib import pyplot
 
  image = pyplot.imread(data)  # crash on py3.x
  pyplot.imshow(image)
  pyplot.show()
  #
  But as you can see, the Python 3 version requires the addition of
  BytesIO and read(). I take it that this is not supposed to be the case.

 It works for X.png, not for X.jpg. The call of imread() fails then.
 Tested also under 3.4/Anaconda.

 Jerzy Karczmarczuk



 --
 Dive into the World of Parallel Programming The Go Parallel Website,
 sponsored
 by Intel and developed in partnership with Slashdot Media, is your hub for
 all
 things parallel software development, from weekly thought leadership blogs
 to
 news, videos, case studies, tutorials and more. Take a look and join the
 conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Best way to display image from URL in Python3

2015-03-20 Thread Ryan Nelson
Thomas, sorry I missed your email.

I'll see if I can get a PR pulled together soon-ish.

Ryan

On Fri, Mar 20, 2015 at 4:32 PM, Ryan Nelson rnelsonc...@gmail.com wrote:

 A little update. It seems that this seems to be specific to Linux in some
 way. I tried the original script from the PR under a couple of conditions:
 * on Windows 7 Anaconda Python 2.7 and 3.4 -- everything works both
 versions
 * on Anaconda Python 2.7 and 3.4 Linux version -- only the 2.7 version
 works
 * on Gentoo Linux Python 2.7 and 3.4, MPL 1.4.3 -- only the 2.7 version
 works
 Hope that helps.

 Ryan

 On Fri, Mar 20, 2015 at 3:41 PM, Jerzy Karczmarczuk 
 jerzy.karczmarc...@unicaen.fr wrote:


 Le 20/03/2015 16:57, Ryan Nelson a écrit :
  For me, if I change the script from the PR to what is shown below,
  everything works fine in both Python 2.7 and 3.4 (Anaconda
  environments, everything updated):
  ##
  url = 'http://www.libpng.org/pub/png/img_png/pngnow.png'
  try:
  import urllib2
  data = urllib2.urlopen(url)
  except Exception:
  import urllib.request
  from io import BytesIO
  data = BytesIO(urllib.request.urlopen(url).read())
 
  from matplotlib import pyplot
 
  image = pyplot.imread(data)  # crash on py3.x
  pyplot.imshow(image)
  pyplot.show()
  #
  But as you can see, the Python 3 version requires the addition of
  BytesIO and read(). I take it that this is not supposed to be the case.

 It works for X.png, not for X.jpg. The call of imread() fails then.
 Tested also under 3.4/Anaconda.

 Jerzy Karczmarczuk



 --
 Dive into the World of Parallel Programming The Go Parallel Website,
 sponsored
 by Intel and developed in partnership with Slashdot Media, is your hub
 for all
 things parallel software development, from weekly thought leadership
 blogs to
 news, videos, case studies, tutorials and more. Take a look and join the
 conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users



--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] Best way to display image from URL in Python3

2015-03-19 Thread Ryan Nelson
Hello all,

I'm porting over some code that used Py2.7 urllib2.urlopen(url) to grab
some image data from the net and load with pyplot.imread. It doesn't work
quite right in Py3.4. I found a couple of refs:

https://github.com/matplotlib/matplotlib/pull/1650
http://stackoverflow.com/questions/15183170/python-crash-when-downloading-image-as-numpy-array

They suggest io.BytesIO(urllib.request.urlopen(url).read()) as a
replacement for Py3. Is this the best practice? Does anyone know a simpler
way to do this?

Ryan
--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Python shell despite no IPython problems

2015-03-14 Thread Ryan Nelson
Sorry Brenton, I meant for my reply to go to the entire list.

Anyway, in your response, I take it that you meant to say that the window
appears and disappears immediately. Yes?

What happens if you restart the Python interpreter and type the following?
 import matplotlib
 matplotlib.use('TkAgg')
 import matplotlib.pyplot as plt
 plt.plot([1,2,3])
 plt.show()
Does my first example work fine in the IPython interpreter? (Sorry, I'm not
on my Windows machine right now, so I can't tell you if I'm seeing the same
problem.)

Ryan

On Sat, Mar 14, 2015 at 8:21 AM, Brenton Horne brentonhorn...@gmail.com
wrote:

  Yes, a popup window appears but it appears immediately after it appears.

 On 14/03/2015 10:03 PM, Ryan Nelson wrote:

 Brenton,

  Unfortunately, those particular examples are out of date. First of all,
 I would not recommend using pylab at all -- and I think that many other
 folks will give you the same advice. (For reasons that I can describe later
 if you are interested.)

  IPython is a much different beast than the vanilla Python interpreter,
 especially in how it handles GUI stuff. Maybe you could temporarily move
 the matplotlibrc file that you created, and try the following from a
 regular Python session:
   import matplotlib
  matplotlib.use('TkAgg')
  import matplotlib.pyplot as plt
  plt.ion()
  plt.plot([1,2,3])
  The second line is telling MPL what backend to use. (You can set this in
 the rc file later, but let's make sure this isn't the problem for now.) The
 third line imports the pyplot module, which is recommended over pylab. The
 fourth line is turning on interactive plotting. Once you execute the plot
 command on the fifth line, a popup window should appear. Yes?

  Ryan



 On Sat, Mar 14, 2015 at 5:17 AM, Brenton Horne brentonhorn...@gmail.com
 wrote:

  Oh and I have made the mentioned customizations to matplotlibrc
 (although the TkAgg line was already present). My python version is 2.7.9
 and matplotlib version is 1.4.3.

 On 14/03/2015 7:14 PM, Brenton Horne wrote:

 Hi,

 I am on Windows 7 64 bit SP1 and I installed matplotlib via wheels files
 here http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib but now
 whenever I execute plotting commands from the python shell (e.g., the 'hi
 mom' example here
 http://matplotlib.org/1.4.3/users/shell.html?highlight=mailing%20list#other-python-interpreters)
 it seems like as though some window is trying to pop up but nothing does.
 Whereas if I try the the hist example here (
 http://matplotlib.org/1.4.3/users/shell.html?highlight=mailing%20list#ipython-to-the-rescue)
 in IPython I get a graph pop-up that seems fine.

 Thanks for your time,
 Brenton




 --
 Dive into the World of Parallel Programming The Go Parallel Website,
 sponsored
 by Intel and developed in partnership with Slashdot Media, is your hub
 for all
 things parallel software development, from weekly thought leadership
 blogs to
 news, videos, case studies, tutorials and more. Take a look and join the
 conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users




--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Python shell despite no IPython problems

2015-03-14 Thread Ryan Nelson
Brenton,

It's good to know that those other solutions work. Unfortunately, I'm just
sitting down at my Windows 7 computer, and I can't reproduce your problem.
I'm also using the Anaconda Python distribution, which might have different
behavior than your installation method.

However, you're in luck, because there are many, many ways to get IPython
to do what you want. (In fact, anything the Python interpreter does,
IPython does better.) All the possible options, though, can make things a
little tricky... Here's a couple of examples:
C:\ ipython -i filename.py
That will start IPython and automatically load the Python file filename.
That way anything you define in filename will be available in the new
IPython session. Alternatively, you can use the IPython %run magic from
inside an IPython session:
In [1]: %run filename.py
That has the same effect as the first example.

As an alternative, IPython notebooks (
http://ipython.org/ipython-doc/stable/notebook/notebook.html) are a very
nice way to interactively work with some data while also retaining all of
the analysis code in a script-like manner. You can have your plots
displayed in the webpage by typing the following in one of the cells:
import matplotlib.pyplot as plt
%matplotlib inline
You can install this using pip:
C:\ pip install ipython[all]

I'm sorry I couldn't help you with your original problem, but I hope these
suggestions help.

Ryan

On Sat, Mar 14, 2015 at 8:54 AM, Brenton Horne brentonhorn...@gmail.com
wrote:

  On 14/03/2015 10:31 PM, Ryan Nelson wrote:

   import matplotlib
  matplotlib.use('TkAgg')
  import matplotlib.pyplot as plt
  plt.plot([1,2,3])
   plt.show()

 That works fine.

 And

 import matplotlib
  matplotlib.use('TkAgg')
  import matplotlib.pyplot as plt
  plt.ion()
  plt.plot([1,2,3])

 works fine in IPython. I avoid using IPython btw because I don't know how
 to call py files from it. When it comes to python commands I like to save
 them as py files so I don't have to continually type them out. I know how
 to call files in the python shell as I access it via the command prompt
 (i.e., by typing python filename.py).

--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] IPython's matplotlib inline magic is really magic? Actually it might resets axes bounds...

2015-03-13 Thread Ryan Nelson
I'm constructing a multi-plot figure using an IPython notebook (v3) and
matplotlib (v1.4.3) inline magic. I was manually setting the axes bounds,
and I ended up with something like the following:


import matplotlib.pyplot as plt
%matplotlib inline

bottom = 0.12
top = 0.9
left = 0.12
axwidth = (1-(left*2))/3

fig = plt.figure(figsize=(10,4))

ax1 = fig.add_axes((left, bottom, axwidth, top))
ax1.set_title('Title')
#ax1.tick_params(labelleft=False)

ax2 = fig.add_axes((left+axwidth, bottom, axwidth, top),
   sharex=ax1, sharey=ax1)
ax2.tick_params(labelleft=False)

ax3 = fig.add_axes((left+axwidth*2, bottom, axwidth, top),
   sharex=ax1, sharey=ax1)
ax3.tick_params(labelleft=False)

fig.savefig('junk.pdf', format='pdf')
fig.savefig('junk2.png')
###

Obviously, the bottom+top that I've selected is 1, so the axes should go
off the top of the figure. (Stupid, I know...) The axes in both the PDF and
PNG formatted files are clipped by the top of the figure as you would
expect; however, the figure that is displayed in the Notebook looks just
fine. In addition, if you add a title to one of the axes, the figure in
IPython suddenly creates more space for the text. Maybe it is rearranging
the axes information behind the scenes?

I'm curious why this design decision was made. I would say this is a bug.
Now that I know about this behavior, I can easily fix it. But new users
will be baffled when their saved figure looks nothing like the displayed
figure in the notebook.

Ryan
--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] [IPython-dev] IPython's matplotlib inline magic is really magic? Actually it might resets axes bounds...

2015-03-13 Thread Ryan Nelson
Okay. I figured out the problem. You need to pass a dictionary to the
config magic. Here is the relevant code:

%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}

I created a PR with IPython (https://github.com/ipython/ipython/pull/8051)
to add this information to the %matplotlib documentation, so this doesn't
cause confusion for others.

Thanks to all the IPython and MPL devs for these great tools!


On Fri, Mar 13, 2015 at 7:07 PM, Wes Turner wes.tur...@gmail.com wrote:

 Ryan,


 http://wrdrd.github.io/docs/consulting/data-science.html#data-visualization-tools
 On Mar 13, 2015 1:59 PM, Ryan Nelson rnelsonc...@gmail.com wrote:

 I'm constructing a multi-plot figure using an IPython notebook (v3) and
 matplotlib (v1.4.3) inline magic. I was manually setting the axes bounds,
 and I ended up with something like the following:

 
 import matplotlib.pyplot as plt
 %matplotlib inline

 bottom = 0.12
 top = 0.9
 left = 0.12
 axwidth = (1-(left*2))/3

 fig = plt.figure(figsize=(10,4))

 ax1 = fig.add_axes((left, bottom, axwidth, top))
 ax1.set_title('Title')
 #ax1.tick_params(labelleft=False)

 ax2 = fig.add_axes((left+axwidth, bottom, axwidth, top),
sharex=ax1, sharey=ax1)
 ax2.tick_params(labelleft=False)

 ax3 = fig.add_axes((left+axwidth*2, bottom, axwidth, top),
sharex=ax1, sharey=ax1)
 ax3.tick_params(labelleft=False)

 fig.savefig('junk.pdf', format='pdf')
 fig.savefig('junk2.png')
 ###

 Obviously, the bottom+top that I've selected is 1, so the axes should go
 off the top of the figure. (Stupid, I know...) The axes in both the PDF and
 PNG formatted files are clipped by the top of the figure as you would
 expect; however, the figure that is displayed in the Notebook looks just
 fine. In addition, if you add a title to one of the axes, the figure in
 IPython suddenly creates more space for the text. Maybe it is rearranging
 the axes information behind the scenes?

 I'm curious why this design decision was made. I would say this is a bug.
 Now that I know about this behavior, I can easily fix it. But new users
 will be baffled when their saved figure looks nothing like the displayed
 figure in the notebook.

 Ryan

 ___
 IPython-dev mailing list
 ipython-...@scipy.org
 http://mail.scipy.org/mailman/listinfo/ipython-dev


 ___
 IPython-dev mailing list
 ipython-...@scipy.org
 http://mail.scipy.org/mailman/listinfo/ipython-dev


--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] IPython's matplotlib inline magic is really magic? Actually it might resets axes bounds...

2015-03-13 Thread Ryan Nelson
Thanks Tom.

Your hint led me to the following page:
https://github.com/ipython/ipython/blob/aab20bf85126f5b1da857193c446aebe6346acec/docs/source/whatsnew/version2.0.rst#other-changes
So it seems that this change is quite old, and I never noticed it before...
The suggestion on that page requires some incantation of the %config magic.
I tried this:
%config InlineBackend.print_figure_kwargs.bbox_inches = None
Which silently passes, but doesn't change the behavior.

Your rational for IPython's use of this kwarg by default is sound, and I
understand that there are valid use cases for it in some circumstances.
However, I still think this is problematic. I like MPL because you can make
a plot to your exact specifications -- but setting this kind of behavior by
default (without a well documented fix) feels a little Microsoft
Office-y... That being said, I really don't care all that much. IPython is
a fantastic tool. I'll just move my plotting code to a separate script and
tweak things there. (But then I won't be able to share the notebook with my
fancy plot embedded except as an external image. Can't have everything.)

I actually don't want any sort of 'tight' layout; however, just for
reference, the `tight_layout` function throws an error in my example.

Ryan




On Fri, Mar 13, 2015 at 4:03 PM, Thomas Caswell tcasw...@gmail.com wrote:

 This is due to the fact that by default the inline backend saves the pngs
 using `boundingbox_inches='tight'`.  The design goal on the mpl side of
 this kwargs was to trim off extra whitespace, but the way it is implemented
 works just as effectively to expand to fit artists that fall outside of the
 figure.  I assume the choice to make this the default in inline was to
 waste as little space as possible.

 A possibly more reliable method to get the same effect is to use
 `tight_layout` (see http://matplotlib.org/users/tight_layout_guide.html)

 There was talk of replacing that implementation with a linear constraint
 solver, but not much progress has been made in that direction (see
 https://github.com/matplotlib/matplotlib/issues/1109)

 Tom

 On Fri, Mar 13, 2015 at 3:01 PM Ryan Nelson rnelsonc...@gmail.com wrote:

 I'm constructing a multi-plot figure using an IPython notebook (v3) and
 matplotlib (v1.4.3) inline magic. I was manually setting the axes bounds,
 and I ended up with something like the following:

 
 import matplotlib.pyplot as plt
 %matplotlib inline

 bottom = 0.12
 top = 0.9
 left = 0.12
 axwidth = (1-(left*2))/3

 fig = plt.figure(figsize=(10,4))

 ax1 = fig.add_axes((left, bottom, axwidth, top))
 ax1.set_title('Title')
 #ax1.tick_params(labelleft=False)

 ax2 = fig.add_axes((left+axwidth, bottom, axwidth, top),
sharex=ax1, sharey=ax1)
 ax2.tick_params(labelleft=False)

 ax3 = fig.add_axes((left+axwidth*2, bottom, axwidth, top),
sharex=ax1, sharey=ax1)
 ax3.tick_params(labelleft=False)

 fig.savefig('junk.pdf', format='pdf')
 fig.savefig('junk2.png')
 ###

 Obviously, the bottom+top that I've selected is 1, so the axes should go
 off the top of the figure. (Stupid, I know...) The axes in both the PDF and
 PNG formatted files are clipped by the top of the figure as you would
 expect; however, the figure that is displayed in the Notebook looks just
 fine. In addition, if you add a title to one of the axes, the figure in
 IPython suddenly creates more space for the text. Maybe it is rearranging
 the axes information behind the scenes?

 I'm curious why this design decision was made. I would say this is a bug.
 Now that I know about this behavior, I can easily fix it. But new users
 will be baffled when their saved figure looks nothing like the displayed
 figure in the notebook.

 Ryan
 
 --
 Dive into the World of Parallel Programming The Go Parallel Website,
 sponsored
 by Intel and developed in partnership with Slashdot Media, is your hub
 for all
 things parallel software development, from weekly thought leadership
 blogs to
 news, videos, case studies, tutorials and more. Take a look and join the
 conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo

Re: [Matplotlib-users] Lorenz -- another Q

2015-03-11 Thread Ryan Nelson
Sometimes a simple text file really does the trick... However, you might
consider saving yourself some future pain by learning some non-text based
storage formats. In the past, I used text files all the time, and they
quickly became limiting, as you've noticed.

I personally like HDF files. There are libraries for these files on all OSs
using many programming languages. Python has at least two: PyTables and
h5py. I've personally used PyTables and find it very user-friendly. Pandas
also has capabilities for interacting with HDF files (via PyTables).

If you are only going to be using Numpy, there are also binary formats such
as .npy, .npz, and memmaps. See `numpy.save`, `numpy.savez`, and
`numpy.memmap`. I don't have much experience here, so I can't say much on
these formats...

Good luck.

Ryan

On Wed, Mar 11, 2015 at 5:15 PM, Benjamin Root ben.r...@ou.edu wrote:

 What 3D array? There shouldn't be any 3D arrays. I suspect that x_t is
 only accidentally 3d by having a shape like (N, M, 1) or (1, N, M).

 Ben Root

 On Wed, Mar 11, 2015 at 5:05 PM, Prahas David Nafissian 
 prahas.mu...@gmail.com wrote:

 Hello,

 Solved the write issue.

 I tried numpy savetxt but it chokes on 3D arrays.

 So I'm doing this:

 x_t.tofile('test3.txt',sep= ,format=%f)

 Only issue -- no end-of-lines. But I can write a quick
 Pascal program to fix this...

 Once again, thanks!


 --
 Dive into the World of Parallel Programming The Go Parallel Website,
 sponsored
 by Intel and developed in partnership with Slashdot Media, is your hub
 for all
 things parallel software development, from weekly thought leadership
 blogs to
 news, videos, case studies, tutorials and more. Take a look and join the
 conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users




 --
 Dive into the World of Parallel Programming The Go Parallel Website,
 sponsored
 by Intel and developed in partnership with Slashdot Media, is your hub for
 all
 things parallel software development, from weekly thought leadership blogs
 to
 news, videos, case studies, tutorials and more. Take a look and join the
 conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Set Ticker useOffset to False in matplotlibrc

2015-02-22 Thread Ryan Nelson
Oops, Julian. Didn't mean to take this off list. Hopefully an updated
matplotlib will help.  (1.2.1 is pretty old. Numerous bug fixes, features,
and improvements have been added.)
Ryan
On Feb 22, 2015 1:23 PM, Julian Irwin julian.ir...@gmail.com wrote:

 Ryan,

 My version is 1.2.1 so I guess that answers that! Thanks, I didn't think
 to check this.

 Julian


 On Sun, Feb 22, 2015 at 10:53 AM, Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Julian,

 What version of matplotlib are you using? The attached rc file works fine
 for me with MPLv1.4.2.

 Ryan

 On Sat, Feb 21, 2015 at 11:56 PM, Julian Irwin julian.ir...@gmail.com
 wrote:

 In the Ticker API docs http://matplotlib.org/api/ticker_api.html the
 following is listed as a valid rc parameter:

 axes.formatter.useoffset=False

 Is there a way to put this in my matplotlibrc?

 I have tried the obvious choice:

 axes.formatter.useoffset : False

 but that give the error

 Bad key axes.formatter.useoffset

 upon importing matplotlib.

 Thanks,

 Julian


 --
 Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
 from Actuate! Instantly Supercharge Your Business Reports and Dashboards
 with Interactivity, Sharing, Native Excel Exports, App Integration  more
 Get technology previously reserved for billion-dollar corporations, FREE

 http://pubads.g.doubleclick.net/gampad/clk?id=190641631iu=/4140/ostg.clktrk
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users




--
Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
from Actuate! Instantly Supercharge Your Business Reports and Dashboards
with Interactivity, Sharing, Native Excel Exports, App Integration  more
Get technology previously reserved for billion-dollar corporations, FREE
http://pubads.g.doubleclick.net/gampad/clk?id=190641631iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Fwd: Keep list of figures or plots and flip through list using UI

2015-02-18 Thread Ryan Nelson
Tom et al.,

I don't know about this exact application... However, a couple of months
ago, I asked on the Scipy mailing list about updating the Scipy cookbook
page for Qt/Matplotlib (
http://wiki.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer),
but I never got a response. The cookbook example is terribly out of date,
so I worked out a pretty simple example that essentially reproduces the Qt
backend plotting window. See my post (
http://mail.scipy.org/pipermail/scipy-dev/2014-December/020258.html) for an
initial version of the code. I may have updated it since that time. If you
are asking for an example for the MPL docs, I would be happy to write my
example up with some picts, if you could tell me where the most appropriate
place in the documentation would be for such an addition.

(However, it sounds like Creator will supersede Designer for Qt5 so...)

Ryan

On Wed, Feb 18, 2015 at 12:31 PM, Thomas Caswell tcasw...@gmail.com wrote:

 A good tutorial on how to make mpl play nice with QtDesigner would be a
 useful thing to have in the documentation.  It would be appreciated if you
 could take a crack at writing that up.

 Tom

 -- Forwarded message -
 From: tenspd137 . dcday...@gmail.com
 Date: Wed Feb 18 2015 at 12:25:10 PM
 Subject: Re: [Matplotlib-users] Keep list of figures or plots and flip
 through list using UI
 To: Thomas Caswell tcasw...@gmail.com


 Funny thing - shortly after I wrote you - I figured it out.  I have a
 GUI/Dialog I created with designer that has a push button which cycles
 between two plots I stored in a list.  If you would like to see my
 code, I would be more than happy to share.  It isn't fabulous, but it
 show the mechanics.  I will also take a look at what you just posted
 above.

 Much appreciated!

 -C




 On Wed, Feb 18, 2015 at 10:19 AM, Thomas Caswell tcasw...@gmail.com
 wrote:
  Please ping the mailing list again (I cc'd the list on this).
 
  See
  https://github.com/tacaswell/leidenfrost/blob/master/
 leidenfrost/gui/reader_gui.py#L636
  (sorry for the code quality, this is a bespoked gui I wrote as part of my
  PhD work, you might be the second person to ever read this code) for a Qt
  object that wraps up a `Figure` in a nice-embedded way.  Using this
 directly
  you can keep a list of these objects around and show/hide them using
  standard Qt methods.  Modifying this a bit you could make this class
 based
  on a standard Qt widget, embed them all in a main window/what have you
 and
  then again use standard Qt methods to show/hide individual plots as you
  wish.
 
  Tom
 
 
  On Wed Feb 18 2015 at 12:00:27 PM tenspd137 . dcday...@gmail.com
 wrote:
 
  Sorry for digging this back up, but I can't seem to get this to work.
  I looked at glue as you suggested, but the page says it only supports
  python 2.7.  As for the Qt examples I can find, all I see how to do is
  to feed a single plot widget different data sets - but nothing on
  dynamically changing the underlying widget and redrawing.  Would you
  maybe take a look at my code and tell me what it is I am missing?  If
  so, I'll send it to you.
 
  Much appreciated.
 
  -C
 
  On Tue, Feb 10, 2015 at 6:48 PM, tenspd137 . dcday...@gmail.com
 wrote:
   No problem - thanks for the reply.  I tried your suggestion of keeping
   a widget for each plot, but I couldn't get the main window to refresh
   correctly - maybe I was doing something wrong.  I'll give it another
   try as soon as I get a chance.  In the meantime, I'll check out glue
   as well - it looks pretty cool.
  
   I might bug you one more time if I can't figure it out, but I am not
   in a hurry and I probably just overlooked something. :)
  
   Thanks and much appreciated!
  
   -C
  
   On Tue, Feb 10, 2015 at 2:44 PM, Thomas Caswell tcasw...@gmail.com
   wrote:
   Sorry this didn't get a response for so long.
  
   The core of the embedding in Qt is at QWidget which contains the
   canvas.
   Anything you want to do with a QWidget you can do with the canvas.
   Independently you need to maintain the mpl level plotting objects
 (the
   Figure, Axes, and Artist objects) (well, you don't _need_ to, you can
   get to
   them through the canvas object, but to keep your self sane I highly
   recommend keeping track of the mpl objects your self, this linkage is
   there
   so that GUI generated draw commands can trigger a re-rendering of the
   figure).
  
   I would just have a widget for each of the plots you want to have and
   then
   cycle which one is visible in the main window, that is probably a lot
   easier
   than trying to attach and detach canvases from Figures.
  
   I would also take a look at glue
   http://www.glueviz.org/en/stable/installation.html who may have
 solved
   many
   of these problems for you.
  
   Tom
  
   On Thu Feb 05 2015 at 1:03:16 PM tenspd137 . dcday...@gmail.com
   wrote:
  
   Hi all,
  
   I often have scripts that make a lot of plots, and I would like to
 be
   able to create the plots 

Re: [Matplotlib-users] axes.get_position() inaccurate until after savefig()?

2015-02-18 Thread Ryan Nelson
I don't have an answer to your question exactly. But I'll just say that
this does make sense. The aspect-corrected axes (after show) is a subset of
what you originally asked for, i.e. the bottom is higher, and the height is
smaller. My guess is that this is not calculated until the final rendering
on save on some computational effort. Otherwise, these values might need to
be recalculated every time you add e.g. a colorbar. There is certainly a
way to trick the plot into rendering, but I wonder if you could post a
small (maybe two axes) version that demonstrates the effect your trying to
accomplish. Perhaps someone might have a simpler/more robust solution.

Ryan

On Wed, Feb 18, 2015 at 4:27 AM, gdm jgabor.as...@gmail.com wrote:

 New matplotlib user here.  Sometimes I like to make figures with multiple
 axes, and have lines that cross multiple axes.  I've run in to problems
 with
 coordinates when doing this.  One such problem is that axes.get_position()
 seems to return incorrect coordinates for an axes with a fixed aspect
 ratio.
 However, after calling pyplot.show()  (or fig.savefig()), it returns the
 correct coordinates.

 Here is some example code:
 #
 import numpy
 import matplotlib.pyplot as plt

 # make up some data
 x = numpy.arange(10)
 y = numpy.sin(x)
 y2 = numpy.cos(x)

 # generate the figure
 fig = plt.figure()

 # setup the first axes
 ax1 = fig.add_subplot(121)
 plt.plot(x,y)

 # setup the second axes with axis ratio
 ax2 = fig.add_subplot(122, aspect=6)
 plt.plot(x, y2)

 # Print out the axes position after various operations
 print aaa, ax2.get_position()

 plt.draw()
 print bbb, ax2.get_position()

 fig.canvas.draw()
 print ccc, ax2.get_position()

 plt.show(block=False)
 print yyy, ax2.get_position()
 ##

 Running this code produces the following output:
 aaa Bbox('array([[ 0.54772727,  0.1   ],\n   [ 0.9   ,  0.9
 ]])')
 bbb Bbox('array([[ 0.54772727,  0.1   ],\n   [ 0.9   ,  0.9
 ]])')
 ccc Bbox('array([[ 0.54772727,  0.1   ],\n   [ 0.9   ,  0.9
 ]])')
 yyy Bbox('array([[ 0.54772727,  0.18686869],\n   [ 0.9   ,
 0.81313131]])')

 P.S.: I think this might be related to an issue noted here:

 http://stackoverflow.com/questions/11900654/get-position-does-strange-things-when-using-a-colorbar





 --
 View this message in context:
 http://matplotlib.1069221.n5.nabble.com/axes-get-position-inaccurate-until-after-savefig-tp44954.html
 Sent from the matplotlib - users mailing list archive at Nabble.com.


 --
 Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
 from Actuate! Instantly Supercharge Your Business Reports and Dashboards
 with Interactivity, Sharing, Native Excel Exports, App Integration  more
 Get technology previously reserved for billion-dollar corporations, FREE

 http://pubads.g.doubleclick.net/gampad/clk?id=190641631iu=/4140/ostg.clktrk
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

--
Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
from Actuate! Instantly Supercharge Your Business Reports and Dashboards
with Interactivity, Sharing, Native Excel Exports, App Integration  more
Get technology previously reserved for billion-dollar corporations, FREE
http://pubads.g.doubleclick.net/gampad/clk?id=190641631iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] Qt4 Designer Example

2015-02-18 Thread Ryan Nelson
Hello list,

A couple months ago, I spent quite a bit of time trying to figure out how
to use Qt designer create a GUI with an embedded MPL window. Unfortunately,
the Scipy cookbook page (
http://wiki.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer) is
very outdated. A recent post (
http://matplotlib.1069221.n5.nabble.com/Re-Keep-list-of-figures-or-plots-and-flip-through-list-using-UI-td44961.html)
brought up some questions about a use case very similar to mine, so I redid
my example and was going to write a quick tutorial for the docs.

Unfortunately, I'm not a Qt guru, so I thought that I would ask on the list
for some advice.  The OP and I were both interested in being able to have a
list of figures that you could select from to change the plot window. The
embedding examples in the docs create subclasses of FigureClass* and embed
the plotting figure/axes/etc. This works but gets tricky, though, when
trying to switch plots. Also, for interactive IPython work, I didn't like
that the plotting objects were mixed in with all the QtGui.QWidget
attributes, which makes introspective searching painful. My solution was to
create a dictionary of matplotlib.figure.Figure objects that had all of the
plotting stuff defined. Then when I select a new plot from the list, the
old one is removed and a new FigureClass object is created using the
selected Figure object. Has anyone else successfully done something like
this? Is there a better way? Also, it seems if I zoom the current plot,
change to a new plot, and change back, the zoom region is retained. Anyone
know how to reset the zoom region?

Attached is my example: window.py is the Designer-created main window and
custommpl.py is the subclass of the main window that I wrote. It's about
as short as I could make it.

Thanks

Ryan
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'test2.ui'
#
# Created: Wed Feb 18 18:20:27 2015
#  by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s

try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8(MainWindow))
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8(centralwidget))
self.gridLayout = QtGui.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName(_fromUtf8(gridLayout))
self.mplfigs = QtGui.QListWidget(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.mplfigs.sizePolicy().hasHeightForWidth())
self.mplfigs.setSizePolicy(sizePolicy)
self.mplfigs.setMaximumSize(QtCore.QSize(200, 16777215))
self.mplfigs.setObjectName(_fromUtf8(mplfigs))
self.gridLayout.addWidget(self.mplfigs, 0, 1, 1, 1)
self.mplwindow = QtGui.QWidget(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.mplwindow.sizePolicy().hasHeightForWidth())
self.mplwindow.setSizePolicy(sizePolicy)
self.mplwindow.setObjectName(_fromUtf8(mplwindow))
self.gridLayout.addWidget(self.mplwindow, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)

self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)

def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate(MainWindow, MainWindow, None))

import sys

from PyQt4 import QtGui

import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)

from window import Ui_MainWindow


class Main(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, ):
super(Main, self).__init__()
self.setupUi(self)
self.mplvl = QtGui.QVBoxLayout(self.mplwindow)
self.mplfigs.itemClicked.connect(self.changefig)
fig = Figure()
self.addmpl(fig)

def addfigs(self, fig_dict):
self.fig_dict = fig_dict
names = list(fig_dict.keys())
self.mplfigs.addItems(names)

def addmpl(self, fig):
self.canvas = FigureCanvas(fig)
   

Re: [Matplotlib-users] [matplotlib-devel] matplotlib v1.4.3

2015-02-17 Thread Ryan Nelson
Tom and other devs,

Thanks for all the hard work! Looking forward to making the upgrade.

Just curious if there is a detailed roadmap for v2 and beyond. I feel like
there have been some rumors that the get/set architecture will be
deprecated at some point.

Ryan

On Tue, Feb 17, 2015 at 4:30 AM, Nelle Varoquaux nelle.varoqu...@gmail.com
wrote:

 Thanks again Thomas for the release !
 Cheers,
 N

 On 17 February 2015 at 06:09, Thomas Caswell tcasw...@gmail.com wrote:
  Hello all,
 
  We are pleased to announce the release of matplotlib v1.4.3!
 
  Wheels, windows binaries and the source tarball are available through
 both
  source-forge [1]  and pypi (via pip).  Additionally the source is
 available
  tarball is available from github [2] and mac-wheels from
  http://wheels.scikit-image.org/.
 
  This is the last planned bug-fix release in the 1.4 series.
 
  Many bugs are fixed including:
 
  fixing drawing of edge-only markers in AGG
  fix run-away memory usage when using %inline or saving with a tight
 bounding
  box with QuadMesh artists
  improvements to wx and tk gui backends
 
  Additionally the webagg and nbagg backends were brought closer to
  feature parity with the desktop backends with the addition of keyboard
  and scroll events thanks to Steven Silvester.
 
  The next planned release will be based on the 1.4.x series but will
 change
  the default colors and be tagged as version v2.0. The target release
 date is
  in the next month or two.
 
  The next feature release will be v2.1 targeted for around SciPy in July.
 
  Tom
 
 
  [1]
 
 https://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.4.3/
 
  [2] https://github.com/matplotlib/matplotlib/releases/tag/v1.4.3
 
 
 
 
 --
  Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
  from Actuate! Instantly Supercharge Your Business Reports and Dashboards
  with Interactivity, Sharing, Native Excel Exports, App Integration  more
  Get technology previously reserved for billion-dollar corporations, FREE
 
 http://pubads.g.doubleclick.net/gampad/clk?id=190641631iu=/4140/ostg.clktrk
  ___
  Matplotlib-devel mailing list
  matplotlib-de...@lists.sourceforge.net
  https://lists.sourceforge.net/lists/listinfo/matplotlib-devel
 


 --
 Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
 from Actuate! Instantly Supercharge Your Business Reports and Dashboards
 with Interactivity, Sharing, Native Excel Exports, App Integration  more
 Get technology previously reserved for billion-dollar corporations, FREE

 http://pubads.g.doubleclick.net/gampad/clk?id=190641631iu=/4140/ostg.clktrk
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

--
Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
from Actuate! Instantly Supercharge Your Business Reports and Dashboards
with Interactivity, Sharing, Native Excel Exports, App Integration  more
Get technology previously reserved for billion-dollar corporations, FREE
http://pubads.g.doubleclick.net/gampad/clk?id=190641631iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] MultipleLocator and MaxNLocator

2015-02-14 Thread Ryan Nelson
Tommy, (Sorry for the doubleup. I just realized I forgot to hit reply-all.)

Do you want to remove the tick at 0 and only have 5,10, etc.? Could you
just do something like this instead:

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_xticks(range(5,11,5))
ax1.plot(range(11))
plt.show()

Ryan


On Sat, Feb 14, 2015 at 10:47 AM, Tommy Carstensen 
tommy.carsten...@gmail.com wrote:

 Thanks for you answer Eric. I had to get some sleep before trying out
 things. I currently have the code below, but it does not remove the
 zero value tick. It removes the tick at 5 and 10 however.

 import matplotlib.pyplot as plt
 from matplotlib.ticker import MultipleLocator
 fig = plt.figure()
 ax1 = fig.add_subplot(111)
 ax1.xaxis.set_major_locator(MultipleLocator(5))
 xticks = ax1.xaxis.get_major_ticks()
 #xticks[0].label1.set_visible(False)
 #xticks[-1].label1.set_visible(False)
 ax1.set_xticks(ax1.get_xticks()[1:-1])
 ax1.plot(list(range(11)))
 plt.show()

 On Sat, Feb 14, 2015 at 2:01 AM, Eric Firing efir...@hawaii.edu wrote:
  On 2015/02/13 3:29 PM, Tommy Carstensen wrote:
  Is it possible to combine MultipleLocator and MaxNLocator? One seems
  to erase the effect of the other.
 
  They are for different situations.  MultipleLocator is for when you know
  what you want your tick interval to be; MaxNLocator is for when you
  don't know that, but you do know roughly how many ticks you want, and
  what sort of numerical intervals are acceptable.
 
  Eric
 
 
 
 --
  Dive into the World of Parallel Programming. The Go Parallel Website,
  sponsored by Intel and developed in partnership with Slashdot Media, is
 your
  hub for all things parallel software development, from weekly thought
  leadership blogs to news, videos, case studies, tutorials and more. Take
 a
  look and join the conversation now. http://goparallel.sourceforge.net/
  ___
  Matplotlib-users mailing list
  Matplotlib-users@lists.sourceforge.net
  https://lists.sourceforge.net/lists/listinfo/matplotlib-users


 --
 Dive into the World of Parallel Programming. The Go Parallel Website,
 sponsored by Intel and developed in partnership with Slashdot Media, is
 your
 hub for all things parallel software development, from weekly thought
 leadership blogs to news, videos, case studies, tutorials and more. Take a
 look and join the conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

--
Dive into the World of Parallel Programming. The Go Parallel Website,
sponsored by Intel and developed in partnership with Slashdot Media, is your
hub for all things parallel software development, from weekly thought
leadership blogs to news, videos, case studies, tutorials and more. Take a
look and join the conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] MultipleLocator and MaxNLocator

2015-02-14 Thread Ryan Nelson
Tommy,

I'm sorry. I forgot to hit send all *again*. Below is my original message,
but the function I wrote is updated because it wasn't exactly correct

Ah. I was working on something to help out, so I'm just seeing Eric's very
elegant solution, which I have yet to try. However, I feel like you might
run into some problems if you always drop the first tick. For example, try
this plot:
__
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np
xs = np.linspace(2,12,1000)
ys = np.sin(xs)
n = 5
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(xs, ys)
ax1.xaxis.set_major_locator(MultipleLocator(5))
plt.show()
_
In this case, dropping the first tick will result in only one tick on the
screen.

What is your use-case? Are you annoyed that the axis labels are overlapping
at the far left? If that's the case, here's a little function (trimticks)
that I whipped up that might help. It drops the far left or far right label
if it is exactly at the edge of the axes. Should work for y axes as well.
_
def trimticks(ax, n=5):
xmin, xmax = ax.get_xlim()
if xmin%n == 0:
xmin = xmin+n
else:
xmin = xmin + n - xmin%n

if not xmax%n == 0:
xmax = xmax + n - xmax%n

ticks = np.arange(xmin, xmax, n)
ax.set_xticks(ticks)

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np
xs = np.linspace(0,20,1)
ys = np.sin(xs)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(xs, ys)
trimticks(ax1)
plt.show()

___


On Sat, Feb 14, 2015 at 1:45 PM, Tommy Carstensen 
tommy.carsten...@gmail.com wrote:

 Erik, that doesn't seem to work either. I tried this:

 import matplotlib.pyplot as plt
 from matplotlib.ticker import MultipleLocator
 class TrimmedMultipleLocator(MultipleLocator):
  def tick_values(self, vmin, vmax):
  return MultipleLocator.tick_values(self, vmin, vmax)[2:]
 fig = plt.figure()
 ax1 = fig.add_subplot(111)
 ax1.xaxis.set_major_locator(TrimmedMultipleLocator(5))
 #xticks[0].label1.set_visible(False)
 #xticks[-1].label1.set_visible(False)
 #ax1.set_xticks(ax1.xaxis.get_major_ticks()[1:-1])
 ax1.plot(list(range(21)))
 plt.show()

 Here is an example of the use of prune='lower', but it does not allow
 one to set the tick step size:

 http://stackoverflow.com/questions/9422587/overlapping-y-axis-tick-label-and-x-axis-tick-label-in-matplotlib

 I think my best bet is to just set those ticks manually.

 On Sat, Feb 14, 2015 at 6:19 PM, Eric Firing efir...@hawaii.edu wrote:
  On 2015/02/14 7:33 AM, Tommy Carstensen wrote:
  Thanks again Ryan. That's exactly what I want to achieve; i.e. remove
  the tick at 0 and only keep 5 and 10. Your solution works, but it's a
  bit of hack to use magic constants. I could however get those values
  from the xlim.
 
  Eric, I would describe the desired tick placement algorithm as
  removing the first tick on the axis. It can be achieved like this:
  ax1.xaxis.set_major_locator(MaxNLocator(prune='lower'))
 
  Aha! The problem is that the MaxNLocator is the only one with the prune
  kwarg.  It could be added to the MultipleLocator.  For now, though, you
  can make your own specialized Locator, hardwired to omit the first tick,
  like this:
 
  from matplotlib.ticker import MultipleLocator
 
  class TrimmedMultipleLocator(MultipleLocator):
   def tick_values(self, vmin, vmax):
   return MultipleLocator.tick_values(self, vmin, vmax)[1:]
 
  then just use
 
  ax1.xaxis.set_major_locator(TrimmedMultipleLocator(5))
 
  I haven't tested it--but give it a try.  What it is doing is making a
  subclass of MultipleLocator, and altering only the one little bit of its
  behavior that you want to modify.  Everything else is automatically
  inherited from the base class, MultipleLocator.
 
  Eric
 
 
 
  But that then overrides this:
  ax1.xaxis.set_major_locator(MultipleLocator(5))
 
  On Sat, Feb 14, 2015 at 5:27 PM, Ryan Nelson rnelsonc...@gmail.com
 wrote:
  Tommy, (Sorry for the doubleup. I just realized I forgot to hit
 reply-all.)
 
  Do you want to remove the tick at 0 and only have 5,10, etc.? Could
 you just
  do something like this instead:
 
  import matplotlib.pyplot as plt
  from matplotlib.ticker import MultipleLocator
  fig = plt.figure()
  ax1 = fig.add_subplot(111)
  ax1.set_xticks(range(5,11,5))
  ax1.plot(range(11))
  plt.show()
 
  Ryan
 
 
  On Sat, Feb 14, 2015 at 10:47 AM, Tommy Carstensen
  tommy.carsten...@gmail.com wrote:
 
  Thanks for you answer Eric. I had to get some sleep before trying out
  things. I currently have the code below, but it does not remove the
  zero value tick. It removes the tick at 5 and 10 however.
 
  import matplotlib.pyplot as plt
  from matplotlib.ticker import MultipleLocator
  fig = plt.figure()
  ax1 = fig.add_subplot(111)
  ax1.xaxis.set_major_locator(MultipleLocator(5))
  xticks = ax1.xaxis.get_major_ticks()
  #xticks[0].label1

Re: [Matplotlib-users] horizontal alignment of a secondary y-axis

2015-02-14 Thread Ryan Nelson
Tommy,

I'll try to answer your points in order:

1) Oops. That should have been xticks.
import matplotlib.pyplot as plt
plt.plot([1,3,2])
ticks, labels = plt.xticks()
plt.xticks(ticks, horizontalalignment='left')
plt.show()


2) Sorry for the ambiguity. OO is short for object-oriented. There are
two different approaches that people tend to use to make plots (although
they can be mixed): 1) the pyplot way, which uses the pyplot wrapper
functions and 2) the object-oriented way, which modifies the objects
directly. This is what you did in your example where you snag the axes
objects and operate on them directly. The OO way is ultimately more
powerful, because the pyplot wrapper functions override some of your
control. For example, because you want twin axes, you might not be able to
use the pyplot.xticks function (Others, correct me if I'm wrong.), and you
lose some fine control. See next example.

3) I know it *seems* like the for loop is an ugly hack. However, you have
to realize that this ultimately gives you a TON of control. Let's say, for
example, that you wanted only one of the labels to be large and red to
highlight a certain value. Using a modified version of your example, we get
this:
__
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
labels = ax2.yaxis.get_ticklabels()
[l.set_horizontalalignment('right') for l in labels]
labels[2].set_color('red')
labels[2].set_fontsize(20)
ax2.tick_params(pad=20)
ax1.plot(list(range(11)))
ax1.set_xlim(0,10)
ax2.set_ylim(0,10)
plt.show()

I personally think that this level of control is very, very cool and one of
the big selling points for MPL in general.

Okay. If you want to set the alignment all the time, there might be a way
to control this with matplotlibrc or style sheets:
http://matplotlib.org/users/customizing.html
http://matplotlib.org/users/style_sheets.html
However, I'm not the biggest fan of changing matplotlibrc. Mostly because
if others try to reproduce your plots, they also need your rc file as well.
I haven't used style sheets yet, but that might be a fix to this issue (for
me at least).

Hope that helps.

Ryan

On Sat, Feb 14, 2015 at 10:30 AM, Tommy Carstensen 
tommy.carsten...@gmail.com wrote:

 Hi Ryan,

 Thanks for your answer. Sorry for not replying sooner. I fell asleep
 shortly after sending my question.

 What is the OO way?

 Your 1st solution gives:
 AttributeError: 'module' object has no attribute 'ticks'

 I modified your 2nd solution to accommodate my wishes and needs:
 import matplotlib.pyplot as plt
 fig = plt.figure()
 ax1 = fig.add_subplot(111)
 ax2 = ax1.twinx()
 for label in ax2.yaxis.get_ticklabels():
 label.set_horizontalalignment('right')
 ax2.tick_params(pad=20)
 ax1.plot(list(range(11)))
 ax1.set_xlim(0,10)
 ax2.set_ylim(0,10)
 plt.show()

 It seems like an awful hack with that for loop, but it works. I'm not
 sure, why the secondary right hand side axis don't have right aligned
 labels by default. That would make a lot of sense. It would be great,
 if I could set the horizontal alignment without having to use a for
 loop. It's just plain ugly. In gnuplot it's as simple as this:
 set ytics right

 Thanks for your help and providing me with a solution.

 Tommy

 On Sat, Feb 14, 2015 at 1:31 AM, Ryan Nelson rnelsonc...@gmail.com
 wrote:
  Tommy,
 
  You are probably looking for pyplot.xticks. For example, you might want
  something along these lines:
 
  import matplotlib.pyplot as plt
  plt.plot([1,3,2])
  # We'll do this to get the autogenerated positions
  ticks, labels = plt.xticks()
  plt.ticks(ticks, horizontalalignment='left')
  plt.show()
 
  Or if your using the OO way:
 
  import matplotlib.pyplot as plt
  fig = plt.figure()
  ax = fig.add_subplot(111)
  ax.plot([1,3,2])
  labels = ax.get_xticklabels()
  [l.set_horizontalalignment('left') for l in labels]
  plt.show()
 
  I think that's the best way. Hope it helps.
 
  Ryan
 
 
 
  On Fri, Feb 13, 2015 at 7:29 PM, Tommy Carstensen
  tommy.carsten...@gmail.com wrote:
 
  How can I set the horizontal alignment of a secondary y-axis to
  'right'? Currently the numbers are glued to the axis. I want the axis
  values to be right aligned integers. Thanks.
 
 
 
 --
  Dive into the World of Parallel Programming. The Go Parallel Website,
  sponsored by Intel and developed in partnership with Slashdot Media, is
  your
  hub for all things parallel software development, from weekly thought
  leadership blogs to news, videos, case studies, tutorials and more.
 Take a
  look and join the conversation now. http://goparallel.sourceforge.net/
  ___
  Matplotlib-users mailing list
  Matplotlib-users@lists.sourceforge.net
  https://lists.sourceforge.net/lists/listinfo/matplotlib-users
 
 


 --
 Dive into the World

Re: [Matplotlib-users] MultipleLocator and MaxNLocator

2015-02-14 Thread Ryan Nelson
Yep. I see your problem. My function and Eric's object should help here.

A sore-spot with many folks coming over to Matplotlib from X is the fact
that MPL does not calculate the size of text until the plot is generated.
That means it doesn't always get text positioning, etc. exactly correct.
That takes a little getting used to, and for me, it is minor.

Admit it, Gnuplot as it's quirks as well :)  I always hated that it
wouldn't cut off some markers at the edge of the screen. For example, with
Gnuplot 4.6rev5 the following
plot x with points ps 7
Leads to a bunch of markers running over the axes limits. (Maybe there is a
way to fix this now. Many years ago that was not the case.)

Ryan

On Sat, Feb 14, 2015 at 2:18 PM, Tommy Carstensen 
tommy.carsten...@gmail.com wrote:

 Ryan, my use case is indeed that I want to avoid overlapping ticks and
 I want to avoid them by not displaying them. Here is a guy with the
 same problem:

 http://stackoverflow.com/questions/9422587/overlapping-y-axis-tick-label-and-x-axis-tick-label-in-matplotlib

 Here is the problem at the top left of my plot:
 www.tommycarstensen.com/matplotlib.png

 I'll just set the ticks manually. Sadly seems like the easiest thing to do.

 On Sat, Feb 14, 2015 at 7:01 PM, Ryan Nelson rnelsonc...@gmail.com
 wrote:
  Tommy,
 
  I'm sorry. I forgot to hit send all *again*. Below is my original
 message,
  but the function I wrote is updated because it wasn't exactly correct
 
  Ah. I was working on something to help out, so I'm just seeing Eric's
 very
  elegant solution, which I have yet to try. However, I feel like you might
  run into some problems if you always drop the first tick. For example,
 try
  this plot:
  __
  import matplotlib.pyplot as plt
  from matplotlib.ticker import MultipleLocator
  import numpy as np
  xs = np.linspace(2,12,1000)
  ys = np.sin(xs)
  n = 5
  fig = plt.figure()
  ax1 = fig.add_subplot(111)
  ax1.plot(xs, ys)
  ax1.xaxis.set_major_locator(MultipleLocator(5))
  plt.show()
  _
  In this case, dropping the first tick will result in only one tick on the
  screen.
 
  What is your use-case? Are you annoyed that the axis labels are
 overlapping
  at the far left? If that's the case, here's a little function (trimticks)
  that I whipped up that might help. It drops the far left or far right
 label
  if it is exactly at the edge of the axes. Should work for y axes as well.
  _
  def trimticks(ax, n=5):
  xmin, xmax = ax.get_xlim()
  if xmin%n == 0:
  xmin = xmin+n
  else:
  xmin = xmin + n - xmin%n
 
  if not xmax%n == 0:
  xmax = xmax + n - xmax%n
 
  ticks = np.arange(xmin, xmax, n)
  ax.set_xticks(ticks)
 
  import matplotlib.pyplot as plt
  from matplotlib.ticker import MultipleLocator
  import numpy as np
  xs = np.linspace(0,20,1)
  ys = np.sin(xs)
  fig = plt.figure()
  ax1 = fig.add_subplot(111)
  ax1.plot(xs, ys)
  trimticks(ax1)
  plt.show()
 
  ___
 
 
  On Sat, Feb 14, 2015 at 1:45 PM, Tommy Carstensen
  tommy.carsten...@gmail.com wrote:
 
  Erik, that doesn't seem to work either. I tried this:
 
  import matplotlib.pyplot as plt
  from matplotlib.ticker import MultipleLocator
  class TrimmedMultipleLocator(MultipleLocator):
   def tick_values(self, vmin, vmax):
   return MultipleLocator.tick_values(self, vmin, vmax)[2:]
  fig = plt.figure()
  ax1 = fig.add_subplot(111)
  ax1.xaxis.set_major_locator(TrimmedMultipleLocator(5))
  #xticks[0].label1.set_visible(False)
  #xticks[-1].label1.set_visible(False)
  #ax1.set_xticks(ax1.xaxis.get_major_ticks()[1:-1])
  ax1.plot(list(range(21)))
  plt.show()
 
  Here is an example of the use of prune='lower', but it does not allow
  one to set the tick step size:
 
 
 http://stackoverflow.com/questions/9422587/overlapping-y-axis-tick-label-and-x-axis-tick-label-in-matplotlib
 
  I think my best bet is to just set those ticks manually.
 
  On Sat, Feb 14, 2015 at 6:19 PM, Eric Firing efir...@hawaii.edu
 wrote:
   On 2015/02/14 7:33 AM, Tommy Carstensen wrote:
   Thanks again Ryan. That's exactly what I want to achieve; i.e. remove
   the tick at 0 and only keep 5 and 10. Your solution works, but it's a
   bit of hack to use magic constants. I could however get those values
   from the xlim.
  
   Eric, I would describe the desired tick placement algorithm as
   removing the first tick on the axis. It can be achieved like this:
   ax1.xaxis.set_major_locator(MaxNLocator(prune='lower'))
  
   Aha! The problem is that the MaxNLocator is the only one with the
 prune
   kwarg.  It could be added to the MultipleLocator.  For now, though,
 you
   can make your own specialized Locator, hardwired to omit the first
 tick,
   like this:
  
   from matplotlib.ticker import MultipleLocator
  
   class TrimmedMultipleLocator(MultipleLocator):
def tick_values(self, vmin, vmax):
return MultipleLocator.tick_values(self, vmin, vmax)[1:]
  
   then just

Re: [Matplotlib-users] horizontal alignment of a secondary y-axis

2015-02-14 Thread Ryan Nelson
Tommy,

It would be helpful if you included a more complete example that
illustrates the problem. If you are setting the text size yourself,
couldn't you adjust the padding as such pad=20/txt_size. Then the padding
will be inversely proportional to the size of the text.

I suspect this is related to the text-rendering size issue that I mentioned
in the other thread. I think you could do something like the following to
get the extent of the label:
http://stackoverflow.com/a/8078114/2662077
Then you could adjust the padding very precisely.

There might be an easier solution for your problem, but without an example,
it is hard to say.

Ryan

On Sat, Feb 14, 2015 at 2:54 PM, Tommy Carstensen 
tommy.carsten...@gmail.com wrote:

 Ryan, do you know, if there is any way I can make the padding
 dependent on the tick label sizes?
 for label in ax2.yaxis.get_ticklabels():
 label.set_horizontalalignment('right')
 ax2.tick_params(pad=20)

 When the numbers are large, then they are glued to the secondary
 y-axis. When they are small, then they are hovering far away from it.

 On Sat, Feb 14, 2015 at 7:20 PM, Ryan Nelson rnelsonc...@gmail.com
 wrote:
  You're welcome, Tommy. I used gnuplot many years ago, but I've been much
  happier now that I know MPL.
 
  A gnuplot-MPL Rosetta Stone might be a useful blog post for someone. I
  haven't used gnuplot in so long that I don't think I could do this
 myself.
 
  R
 
  On Sat, Feb 14, 2015 at 12:28 PM, Tommy Carstensen
  tommy.carsten...@gmail.com wrote:
 
  Whoa, thanks for a great answer Ryan. I can see, why the level of
  control MPL gives you is a great sales pitch. It's one of the reasons,
  why I switched from gnuplot after using it for many years and making
  many cool plots. The MPL learning curve has just been a bit steep,
  when you are used to plot whatever you want.
 
  On Sat, Feb 14, 2015 at 5:06 PM, Ryan Nelson rnelsonc...@gmail.com
  wrote:
   Tommy,
  
   I'll try to answer your points in order:
  
   1) Oops. That should have been xticks.
   import matplotlib.pyplot as plt
   plt.plot([1,3,2])
   ticks, labels = plt.xticks()
   plt.xticks(ticks, horizontalalignment='left')
   plt.show()
  
  
   2) Sorry for the ambiguity. OO is short for object-oriented. There
 are
   two
   different approaches that people tend to use to make plots (although
   they
   can be mixed): 1) the pyplot way, which uses the pyplot wrapper
   functions
   and 2) the object-oriented way, which modifies the objects directly.
   This is
   what you did in your example where you snag the axes objects and
 operate
   on
   them directly. The OO way is ultimately more powerful, because the
   pyplot
   wrapper functions override some of your control. For example, because
   you
   want twin axes, you might not be able to use the pyplot.xticks
 function
   (Others, correct me if I'm wrong.), and you lose some fine control.
 See
   next
   example.
  
   3) I know it *seems* like the for loop is an ugly hack. However, you
   have
   to realize that this ultimately gives you a TON of control. Let's say,
   for
   example, that you wanted only one of the labels to be large and red to
   highlight a certain value. Using a modified version of your example,
 we
   get
   this:
   __
   import matplotlib.pyplot as plt
   fig = plt.figure()
   ax1 = fig.add_subplot(111)
   ax2 = ax1.twinx()
   labels = ax2.yaxis.get_ticklabels()
   [l.set_horizontalalignment('right') for l in labels]
   labels[2].set_color('red')
   labels[2].set_fontsize(20)
   ax2.tick_params(pad=20)
   ax1.plot(list(range(11)))
   ax1.set_xlim(0,10)
   ax2.set_ylim(0,10)
   plt.show()
   
   I personally think that this level of control is very, very cool and
 one
   of
   the big selling points for MPL in general.
  
   Okay. If you want to set the alignment all the time, there might be a
   way to
   control this with matplotlibrc or style sheets:
   http://matplotlib.org/users/customizing.html
   http://matplotlib.org/users/style_sheets.html
   However, I'm not the biggest fan of changing matplotlibrc. Mostly
   because if
   others try to reproduce your plots, they also need your rc file as
 well.
   I
   haven't used style sheets yet, but that might be a fix to this issue
   (for me
   at least).
  
   Hope that helps.
  
   Ryan
  
   On Sat, Feb 14, 2015 at 10:30 AM, Tommy Carstensen
   tommy.carsten...@gmail.com wrote:
  
   Hi Ryan,
  
   Thanks for your answer. Sorry for not replying sooner. I fell asleep
   shortly after sending my question.
  
   What is the OO way?
  
   Your 1st solution gives:
   AttributeError: 'module' object has no attribute 'ticks'
  
   I modified your 2nd solution to accommodate my wishes and needs:
   import matplotlib.pyplot as plt
   fig = plt.figure()
   ax1 = fig.add_subplot(111)
   ax2 = ax1.twinx()
   for label in ax2.yaxis.get_ticklabels():
   label.set_horizontalalignment('right')
   ax2.tick_params(pad=20)
   ax1.plot(list(range(11)))
   ax1

Re: [Matplotlib-users] backend_qt4agg

2015-02-12 Thread Ryan Nelson
John,

It's been a little while since I installed QGIS on my machine, but I wonder
if you missed a selection somewhere in the installation process. Can you
reinstall QGIS? (i.e. do you have admin permissions?) There might be a
number of selections you can make when installing, and my guess is that you
missed a selection to have the proper Python libraries installed. Maybe
there is a Full installation option, which puts everything on your
machine. As I said on my installation of QGIS, that code works just fine,
and I'm certain that I haven't done anything special post-install.

Ryan

On Thu, Feb 12, 2015 at 12:37 PM, john polo jp...@mail.usf.edu wrote:

  Ryan,
 I used the first line of your example and this was the result:
 Traceback (most recent call last):
   File input, line 1, in module
   File C:/OSGEO4~1/apps/qgis/./python\qgis\utils.py, line 454, in _import
 mod = _builtin_import(name, globals, locals, fromlist, level)
 ImportError: No module named matplotlib.pyplot

 I'm not sure what the first command is to confirm whether a module is
 installed or not, but it looks like I may need that.
 Thanks, Ben and Ryan.

 John


 On 2/12/2015 10:09 AM, Ryan Nelson wrote:

 John,

  As Ben said, the QGIS Windows installer comes with its own Python
 installation, which doesn't know anything about any other Python install.
 Unfortunately, this apparently makes it rather difficult to install other
 packages. However, QGIS Python already contains Numpy and Matplotlib and
 PyQt4, which is what you need here. From the Plugins dropdown menu, select
 Python Console. In the console that opens at the bottom of the screen, you
 should be able to type (don't type the  characters):
  import matplotlib.pyplot as plt
  plt.plot([1,2,3])
  plt.show()

  On my install of QGIS, that opens a pop-up window with a plot of those
 data points. Does this throw an error for you too?

  Ryan

 On Thu, Feb 12, 2015 at 10:35 AM, john polo jp...@mail.usf.edu wrote:

 Users,
 I am working on Windows 7 with QGIS 2.4. I am trying to get a plugin
 installed in QGIS called Semi-Automatic Classification Plugin to work.
 The plugin is demonstrated here:

 http://fromgistors.blogspot.com/2013/07/working-with-multispectral-bands-in-qgis.html

 The first time I tried to install the QGIS plugin, I got an error
 message that backend_qt4agg was not installed. I installed Python(x,y)
 with Python 2.x, because it seemed like the easiest way to get
 matplotlib and a bunch of other apps/extensions installed at the same
 time with minimal effort. I am not a programmer and I'm not familiar
 with installing things from source and then configuring settings. After
 the Python(x,y) install, I went to QGIS and started again and tried to
 install the plugin. I got the same error message. Please tell me what I
 need to do to get this backend installed in order to get the QGIS plugin
 I want.

 John Polo



 --
 Dive into the World of Parallel Programming. The Go Parallel Website,
 sponsored by Intel and developed in partnership with Slashdot Media, is
 your
 hub for all things parallel software development, from weekly thought
 leadership blogs to news, videos, case studies, tutorials and more. Take a
 look and join the conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users




--
Dive into the World of Parallel Programming. The Go Parallel Website,
sponsored by Intel and developed in partnership with Slashdot Media, is your
hub for all things parallel software development, from weekly thought
leadership blogs to news, videos, case studies, tutorials and more. Take a
look and join the conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] backend_qt4agg

2015-02-12 Thread Ryan Nelson
John,

As Ben said, the QGIS Windows installer comes with its own Python
installation, which doesn't know anything about any other Python install.
Unfortunately, this apparently makes it rather difficult to install other
packages. However, QGIS Python already contains Numpy and Matplotlib and
PyQt4, which is what you need here. From the Plugins dropdown menu, select
Python Console. In the console that opens at the bottom of the screen, you
should be able to type (don't type the  characters):
 import matplotlib.pyplot as plt
 plt.plot([1,2,3])
 plt.show()

On my install of QGIS, that opens a pop-up window with a plot of those data
points. Does this throw an error for you too?

Ryan

On Thu, Feb 12, 2015 at 10:35 AM, john polo jp...@mail.usf.edu wrote:

 Users,
 I am working on Windows 7 with QGIS 2.4. I am trying to get a plugin
 installed in QGIS called Semi-Automatic Classification Plugin to work.
 The plugin is demonstrated here:

 http://fromgistors.blogspot.com/2013/07/working-with-multispectral-bands-in-qgis.html

 The first time I tried to install the QGIS plugin, I got an error
 message that backend_qt4agg was not installed. I installed Python(x,y)
 with Python 2.x, because it seemed like the easiest way to get
 matplotlib and a bunch of other apps/extensions installed at the same
 time with minimal effort. I am not a programmer and I'm not familiar
 with installing things from source and then configuring settings. After
 the Python(x,y) install, I went to QGIS and started again and tried to
 install the plugin. I got the same error message. Please tell me what I
 need to do to get this backend installed in order to get the QGIS plugin
 I want.

 John Polo



 --
 Dive into the World of Parallel Programming. The Go Parallel Website,
 sponsored by Intel and developed in partnership with Slashdot Media, is
 your
 hub for all things parallel software development, from weekly thought
 leadership blogs to news, videos, case studies, tutorials and more. Take a
 look and join the conversation now. http://goparallel.sourceforge.net/
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

--
Dive into the World of Parallel Programming. The Go Parallel Website,
sponsored by Intel and developed in partnership with Slashdot Media, is your
hub for all things parallel software development, from weekly thought
leadership blogs to news, videos, case studies, tutorials and more. Take a
look and join the conversation now. http://goparallel.sourceforge.net/___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] creating a path from multiple sets of xy coordinates (inner and outer outlines)

2014-12-22 Thread Ryan Nelson
Denis,

I've only made simple polygons with MPL, so I don't know the full
capabilities. However, there is another package called Shapely that can
construct polygons like you've defined:
http://toblerity.org/shapely/manual.html#polygons
It also does some set-type stuff, such as intersections, differences, etc.
Might be overkill, but it should do what you want.

Ryan
(Meant to send this to the list as well, Denis. Sorry for the repeat.)

On Mon, Dec 22, 2014 at 6:15 AM, Denis-Alexander Engemann 
denis.engem...@gmail.com wrote:

 Thanks Phil,

 just to make sure I inderstand the logic of PathPatch. Does it cut out
 vertices / paths that are detected to be inside an outline as the star in
 this example?

 -Denis


 2014-12-22 12:09 GMT+01:00 Phil Elson pelson@gmail.com:

 Sorry its taken so long to get an answer, but essentially you want to
 concatenate the outer coordinates with the inner ones (reversed) to
 indicate that it is a hole. There is a pretty (simple) useful example that
 I added a few years ago for demonstrating the use of paths for markers:
 http://matplotlib.org/examples/pylab_examples/marker_path.html

 Constructing a patch from a path is as simple as (untested):

 import matplotlib.patches as mpatches
 patch = mpatches.PathPatch(my_path, facecolor='red', edgecolor='yellow')
 axes.add_patch(patch)


 HTH,

 Phil


 On 19 December 2014 at 23:01, Denis-Alexander Engemann 
 denis.engem...@gmail.com wrote:

 Dear list,

 I would like to create a custom image clipping mask using patches. My
 constraint is that my patch is required to have an outer and multiple inner
 outlines.
 To provide an analogy, think of a mask used for disguise where you leave
 three holes, two for the eyes, one for the mouth.
 I have the xy coordinates for the 'head', and the xy coordinates for
 each of the holes that I don't want to be hidden by the ensuing clipping
 mask.

 What's the matplotlib way to construct my desired path + patch from that?
 Note, it's important in my case to use a patch object. What I need to do
 would not work by simply masking my image using a masked array.

 Any pointer would be highly appreciated --
 Denis


 --
 Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
 from Actuate! Instantly Supercharge Your Business Reports and Dashboards
 with Interactivity, Sharing, Native Excel Exports, App Integration  more
 Get technology previously reserved for billion-dollar corporations, FREE

 http://pubads.g.doubleclick.net/gampad/clk?id=164703151iu=/4140/ostg.clktrk
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users





 --
 Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
 from Actuate! Instantly Supercharge Your Business Reports and Dashboards
 with Interactivity, Sharing, Native Excel Exports, App Integration  more
 Get technology previously reserved for billion-dollar corporations, FREE

 http://pubads.g.doubleclick.net/gampad/clk?id=164703151iu=/4140/ostg.clktrk
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
Dive into the World of Parallel Programming! The Go Parallel Website,
sponsored by Intel and developed in partnership with Slashdot Media, is your
hub for all things parallel software development, from weekly thought
leadership blogs to news, videos, case studies, tutorials and more. Take a
look and join the conversation now. http://goparallel.sourceforge.net___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] fill_between issue

2014-12-09 Thread Ryan Nelson
Ah... That was not clear. I just retried my first example (with
show-savefig) for all of the backends that I have available: Qt4Agg,
TkAgg, PS, PDF, pgf, Cairo, GTK3Cairo, GTK3Agg. All of the *Agg backends
show the same problem: the other backends work as expected. I will file a
bug report now.

Ryan

On Tue, Dec 9, 2014 at 9:50 AM, Benjamin Root ben.r...@ou.edu wrote:

 Interesting. Just to double-check, when you say that it only happens for
 the agg backend, are you saying that backends like tkagg are
 unaffected? I think at this point there is enough information here to file
 a bug report.

 Ben Root

 On Mon, Dec 8, 2014 at 6:14 PM, Ryan Nelson rnelsonc...@gmail.com wrote:

 Final update.

 I've done some more searching, and found a couple more things. It seems
 that this problem occurs with the backend set to Agg
 (`matplotlib.use(agg)), so it isn't related to the interactive backends.
 In addition, the problem does not occur with a random Polygon object added
 to an axes; however, I do see the problem when the same polygon is added to
 the axes as a PolyCollection. See code below.

 Ryan

 #
 import numpy as np
 import matplotlib
 matplotlib.use(Agg)
 import matplotlib.pyplot as plt
 from matplotlib.collections import PolyCollection

 x = np.linspace(0, np.pi*2, 1000)
 y = np.sin(x)

 ax = plt.axes()
 data =np.array([(0,0), (1,0), (1,1), (0,1)])

 # These three lines work fine.
 poly = plt.Polygon(data)
 poly.set_linewidth(0)
 ax.add_patch(poly)

 # Comment out the three lines above
 # Uncomment next three lines, does not work.
 #col = PolyCollection([data])
 #col.set_linewidth(0.0)
 #ax.add_collection(col)

 plt.axis([-2, 2, -2, 2])
 plt.savefig('junk')
 #

 On Mon, Dec 8, 2014 at 5:02 PM, Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Update 2.

 I made a new Anaconda Python 2.7 environment and cycled through some
 different MPL versions. Everything works as I would expect in 1.4.0;
 however, moving to 1.4.1 is when the problem occurs. I see this same
 problem if I do the OO commands instead of pyplot.

 import numpy as np
 import matplotlib.pyplot as plt

 x = np.linspace(0, np.pi*2, 1000)
 y = np.sin(x)

 ax = plt.axes()
 fill = ax.fill_between(x, y-0.1, y+0.1)
 fill.set_linewidth(0)

 plt.show()

 On Mon, Dec 8, 2014 at 3:38 PM, Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Update.

 This is a problem also in Anaconda Py3.4 with MPL 1.4.2, but it works
 without a problem on MPL 1.4.0.

 Ryan

 On Mon, Dec 8, 2014 at 12:15 PM, Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Hello all,

 I'm having an issue with fill_between. It seems that setting the
 keyword `linewidth=0` removes the entire patch, rather than the just the
 bounding lines. Example:

 
 import numpy as np
 import matplotlib.pyplot as plt

 x = np.linspace(0, 2*np.pi, 1000)
 y = np.sin(x)

 plt.fill_between(x, y-0.1, y+0.1, linewidth=0) # Setting this !=0
 works fine
 plt.plot(x, y, 'k')
 plt.show()
 

 I'm using MPL version 1.4.2 on Python 2.7.8 (Gentoo Linux). This used
 to work fine before, but maybe there is a new way to do what...

 Thanks

 Ryan







 --
 Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
 from Actuate! Instantly Supercharge Your Business Reports and Dashboards
 with Interactivity, Sharing, Native Excel Exports, App Integration  more
 Get technology previously reserved for billion-dollar corporations, FREE

 http://pubads.g.doubleclick.net/gampad/clk?id=164703151iu=/4140/ostg.clktrk
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users



--
Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
from Actuate! Instantly Supercharge Your Business Reports and Dashboards
with Interactivity, Sharing, Native Excel Exports, App Integration  more
Get technology previously reserved for billion-dollar corporations, FREE
http://pubads.g.doubleclick.net/gampad/clk?id=164703151iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] fill_between issue

2014-12-08 Thread Ryan Nelson
Hello all,

I'm having an issue with fill_between. It seems that setting the keyword
`linewidth=0` removes the entire patch, rather than the just the bounding
lines. Example:


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 1000)
y = np.sin(x)

plt.fill_between(x, y-0.1, y+0.1, linewidth=0) # Setting this !=0 works fine
plt.plot(x, y, 'k')
plt.show()


I'm using MPL version 1.4.2 on Python 2.7.8 (Gentoo Linux). This used to
work fine before, but maybe there is a new way to do what...

Thanks

Ryan
--
Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
from Actuate! Instantly Supercharge Your Business Reports and Dashboards
with Interactivity, Sharing, Native Excel Exports, App Integration  more
Get technology previously reserved for billion-dollar corporations, FREE
http://pubads.g.doubleclick.net/gampad/clk?id=164703151iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] fill_between issue

2014-12-08 Thread Ryan Nelson
Update.

This is a problem also in Anaconda Py3.4 with MPL 1.4.2, but it works
without a problem on MPL 1.4.0.

Ryan

On Mon, Dec 8, 2014 at 12:15 PM, Ryan Nelson rnelsonc...@gmail.com wrote:

 Hello all,

 I'm having an issue with fill_between. It seems that setting the keyword
 `linewidth=0` removes the entire patch, rather than the just the bounding
 lines. Example:

 
 import numpy as np
 import matplotlib.pyplot as plt

 x = np.linspace(0, 2*np.pi, 1000)
 y = np.sin(x)

 plt.fill_between(x, y-0.1, y+0.1, linewidth=0) # Setting this !=0 works
 fine
 plt.plot(x, y, 'k')
 plt.show()
 

 I'm using MPL version 1.4.2 on Python 2.7.8 (Gentoo Linux). This used to
 work fine before, but maybe there is a new way to do what...

 Thanks

 Ryan



--
Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
from Actuate! Instantly Supercharge Your Business Reports and Dashboards
with Interactivity, Sharing, Native Excel Exports, App Integration  more
Get technology previously reserved for billion-dollar corporations, FREE
http://pubads.g.doubleclick.net/gampad/clk?id=164703151iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] fill_between issue

2014-12-08 Thread Ryan Nelson
Update 2.

I made a new Anaconda Python 2.7 environment and cycled through some
different MPL versions. Everything works as I would expect in 1.4.0;
however, moving to 1.4.1 is when the problem occurs. I see this same
problem if I do the OO commands instead of pyplot.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, np.pi*2, 1000)
y = np.sin(x)

ax = plt.axes()
fill = ax.fill_between(x, y-0.1, y+0.1)
fill.set_linewidth(0)

plt.show()

On Mon, Dec 8, 2014 at 3:38 PM, Ryan Nelson rnelsonc...@gmail.com wrote:

 Update.

 This is a problem also in Anaconda Py3.4 with MPL 1.4.2, but it works
 without a problem on MPL 1.4.0.

 Ryan

 On Mon, Dec 8, 2014 at 12:15 PM, Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Hello all,

 I'm having an issue with fill_between. It seems that setting the keyword
 `linewidth=0` removes the entire patch, rather than the just the bounding
 lines. Example:

 
 import numpy as np
 import matplotlib.pyplot as plt

 x = np.linspace(0, 2*np.pi, 1000)
 y = np.sin(x)

 plt.fill_between(x, y-0.1, y+0.1, linewidth=0) # Setting this !=0 works
 fine
 plt.plot(x, y, 'k')
 plt.show()
 

 I'm using MPL version 1.4.2 on Python 2.7.8 (Gentoo Linux). This used to
 work fine before, but maybe there is a new way to do what...

 Thanks

 Ryan




--
Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
from Actuate! Instantly Supercharge Your Business Reports and Dashboards
with Interactivity, Sharing, Native Excel Exports, App Integration  more
Get technology previously reserved for billion-dollar corporations, FREE
http://pubads.g.doubleclick.net/gampad/clk?id=164703151iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] fill_between issue

2014-12-08 Thread Ryan Nelson
Final update.

I've done some more searching, and found a couple more things. It seems
that this problem occurs with the backend set to Agg
(`matplotlib.use(agg)), so it isn't related to the interactive backends.
In addition, the problem does not occur with a random Polygon object added
to an axes; however, I do see the problem when the same polygon is added to
the axes as a PolyCollection. See code below.

Ryan

#
import numpy as np
import matplotlib
matplotlib.use(Agg)
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection

x = np.linspace(0, np.pi*2, 1000)
y = np.sin(x)

ax = plt.axes()
data =np.array([(0,0), (1,0), (1,1), (0,1)])

# These three lines work fine.
poly = plt.Polygon(data)
poly.set_linewidth(0)
ax.add_patch(poly)

# Comment out the three lines above
# Uncomment next three lines, does not work.
#col = PolyCollection([data])
#col.set_linewidth(0.0)
#ax.add_collection(col)

plt.axis([-2, 2, -2, 2])
plt.savefig('junk')
#

On Mon, Dec 8, 2014 at 5:02 PM, Ryan Nelson rnelsonc...@gmail.com wrote:

 Update 2.

 I made a new Anaconda Python 2.7 environment and cycled through some
 different MPL versions. Everything works as I would expect in 1.4.0;
 however, moving to 1.4.1 is when the problem occurs. I see this same
 problem if I do the OO commands instead of pyplot.

 import numpy as np
 import matplotlib.pyplot as plt

 x = np.linspace(0, np.pi*2, 1000)
 y = np.sin(x)

 ax = plt.axes()
 fill = ax.fill_between(x, y-0.1, y+0.1)
 fill.set_linewidth(0)

 plt.show()

 On Mon, Dec 8, 2014 at 3:38 PM, Ryan Nelson rnelsonc...@gmail.com wrote:

 Update.

 This is a problem also in Anaconda Py3.4 with MPL 1.4.2, but it works
 without a problem on MPL 1.4.0.

 Ryan

 On Mon, Dec 8, 2014 at 12:15 PM, Ryan Nelson rnelsonc...@gmail.com
 wrote:

 Hello all,

 I'm having an issue with fill_between. It seems that setting the keyword
 `linewidth=0` removes the entire patch, rather than the just the bounding
 lines. Example:

 
 import numpy as np
 import matplotlib.pyplot as plt

 x = np.linspace(0, 2*np.pi, 1000)
 y = np.sin(x)

 plt.fill_between(x, y-0.1, y+0.1, linewidth=0) # Setting this !=0 works
 fine
 plt.plot(x, y, 'k')
 plt.show()
 

 I'm using MPL version 1.4.2 on Python 2.7.8 (Gentoo Linux). This used to
 work fine before, but maybe there is a new way to do what...

 Thanks

 Ryan





--
Download BIRT iHub F-Type - The Free Enterprise-Grade BIRT Server
from Actuate! Instantly Supercharge Your Business Reports and Dashboards
with Interactivity, Sharing, Native Excel Exports, App Integration  more
Get technology previously reserved for billion-dollar corporations, FREE
http://pubads.g.doubleclick.net/gampad/clk?id=164703151iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Plotting large file (NetCDF)

2014-09-09 Thread Ryan Nelson
Raffaele,

As Ben pointed out, you might be creating a lot of in memory Numpy arrays
that you probably don't need/want.

For example, I think (?) slicing all of the variable below:
lons = fh.variables['lon'][:]
is making a copy of all that (mmap'ed) data as a Numpy array in memory. Get
rid of the slice ([:]). Of course, these variables are not Numpy arrays, so
you'll have to change some of your code. For example:
lon_0 = lons.mean()
Will have to become:
lon_0 = np.mean( lons )

If lats and lons are very large sets of data, then meshgrid will make two
very, very large arrays in memory.
For example, try this:
np.meshgrid(np.arange(5), np.arange(5))
The output is two much larger arrays:
[array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]),
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])]
I don't know Basemap at all, so I don't know if this is necessary. You
might be able to force the meshgrid output into a memmap file, but I don't
know how to do that right now. Perhaps someone else has some suggestions.

Hope that helps.

Ryan




On Tue, Sep 9, 2014 at 4:07 AM, Raffaele Quarta raffaele.qua...@linksmt.it
wrote:

  Hi Jody and Ben,

 thanks for your answers.
 I tried to use pcolormesh instead of pcolor and the result is very good!
 For what concern with the memory system problem, I wasn't able to solve it.
 When I tried to use the bigger file, I got the same problem. Attached you
 will find the script that I'm using to make the plot. May be, I didn't
 understand very well how can I use the mmap function.

 Regards,

 Raffaele.


 -Original Message-
 From: Jody Klymak [mailto:jkly...@uvic.ca jkly...@uvic.ca]
 Sent: Mon 9/8/2014 5:46 PM
 To: Benjamin Root
 Cc: Raffaele Quarta; Matplotlib Users
 Subject: Re: [Matplotlib-users] Plotting large file (NetCDF)

 It looks like you are calling `pcolor`.  Can I suggest you try
 `pcolormesh`?  ii

 75 Mb is not a big file!

 Cheers,   Jody


 On Sep 8, 2014, at  7:38 AM, Benjamin Root ben.r...@ou.edu wrote:

  (Keeping this on the mailing list so that others can benefit)
 
  What might be happening is that you are keeping around too many numpy
 arrays in memory than you actually need. Take advantage of memmapping,
 which most netcdf tools provide by default. This keeps the data on disk
 rather than in RAM. Second, for very large images, I would suggest either
 pcolormesh() or just simply imshow() instead of pcolor() as they are more
 way more efficient than pcolor(). In addition, it sounds like you are
 dealing with re-sampled data (at different zoom levels). Does this mean
 that you are re-running contour on re-sampled data? I am not sure what the
 benefit of doing that is if one could just simply do the contour once at
 the highest resolution.
 
  Without seeing any code, though, I can only provide generic suggestions.
 
  Cheers!
  Ben Root
 
 
  On Mon, Sep 8, 2014 at 10:12 AM, Raffaele Quarta 
 raffaele.qua...@linksmt.it wrote:
  Hi Ben,
 
  sorry for the few details that I gave to you. I'm trying to make a
 contour plot of a variable at different zoom levels by using high
 resolution data. The aim is to obtain .PNG output images. Actually, I'm
 working with big data (NetCDF file, dimension is about 75Mb). The current
 Matplotlib version on my UBUNTU 14.04 machine is the 1.3.1 one. My system
 has a RAM capacity of 8Gb.
  Actually, I'm dealing with memory system problems when I try to make a
 plot. I got the error message as follow:
 
  
   cs = m.pcolor(xi,yi,np.squeeze(t))
File /usr/lib/pymodules/python2.7/mpl_toolkits/basemap/__init__.py,
 line 521, in with_transform
  return plotfunc(self,x,y,data,*args,**kwargs)
File /usr/lib/pymodules/python2.7/mpl_toolkits/basemap/__init__.py,
 line 3375, in pcolor
  x = ma.masked_values(np.where(x  1.e20,1.e20,x), 1.e20)
File /usr/lib/python2.7/dist-packages/numpy/ma/core.py, line 2195,
 in masked_values
  condition = umath.less_equal(mabs(xnew - value), atol + rtol *
 mabs(value))
  MemoryError
  
 
  Otherwise, when I try to make a plot of smaller file (such as 5Mb), it
 works very well. I believe that it's not something of wrong in the script.
 It might be a memory system problem.
  I hope that my message is more clear now.
 
  Thanks for the help.
 
  Regards,
 
  Raffaele
 
  -
 
  Sent: Mon 9/8/2014 3:19 PM
  To: Raffaele Quarta
  Cc: Matplotlib Users
  Subject: Re: [Matplotlib-users] Plotting large file (NetCDF)
 
 
 
  You will need to be more specific... much more specific. What kind of
 plot
  are you making? How big is your data? What version of matplotlib are you
  using? How much RAM do you have available compared to the amount of data
  (most slowdowns are actually due to swap-thrashing issues). 

Re: [Matplotlib-users] Setting the tick label font size

2013-10-29 Thread Ryan Nelson
Daniele,

I agree this is perhaps a little overly complicated. (However, once you
figure it out, it does give you a ton of flexibility.)  I played around
with this a bit (thanks IPython!), and I may have figured out what you
wanted to do. I rewrote the example you linked from the MPL website. I
couldn't simplify it much, but it does change the size, location and labels
of the floating y axis.

#

from mpl_toolkits.axes_grid1 import host_subplot

import mpl_toolkits.axisartist as AA

import matplotlib.pyplot as plt


host = host_subplot(111, axes_class=AA.Axes)

plt.subplots_adjust(right=0.75)


par1 = host.twinx()


par2 = host.twinx()

offset = 60

new_fixed_axis = par2.get_grid_helper().new_fixed_axis

par2.axis[right] = new_fixed_axis(loc=right,

axes=par2,

offset=(offset, 0))

par2.axis[right].toggle(all=True)


p1, = host.plot([0, 1, 2], [0, 1, 2], label=Density)

p2, = par1.plot([0, 1, 2], [0, 3, 2], label=Temperature)

p3, = par2.plot([0, 1, 2], [50, 30, 15], label=Velocity)


host.legend()


host.set_xlabel(Distance)

host.set_ylabel(Density)

host.axis[left].label.set_color(p1.get_color())

host.set_xlim(0, 2)

host.set_ylim(0, 2)


par1.set_ylabel(Temperature)

par1.axis[right].label.set_color(p2.get_color())

par1.set_ylim(0, 4)


par2.set_ylabel(Velocity)

par2.set_ylim(1, 65)

par2.yaxis.set_ticks( (20.0, 40.0) )

par2.yaxis.set_ticklabels( ('A', 'B') )

par2.axis[right].label.set_color(p3.get_color())

par2.axis[right].label.set_fontsize(18)

par2.axis[right].major_ticklabels.set_fontsize(14)


plt.show()

##


Hope that helps.


Ryan


On Tue, Oct 29, 2013 at 5:54 AM, Daniele Nicolodi dani...@grinta.netwrote:

 On 29/10/2013 03:11, Ryan Nelson wrote:
  Daniele,
 
  I noticed the same problem with the Qt backend. However, I was looking
  at the documentation on the AxesGrid webpage here:
  http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html
  And I see the following warning:
 
  axes_grid and axisartist (but not axes_grid1) uses a custom Axes class
  (derived from the mpl’s original Axes class). As a side effect, some
  commands (mostly tick-related) do not work. Use axes_grid1 to avoid
  this, or see how things are different in axes_grid and axisartist (LINK
  needed)
 
  Unfortunately, no link. But perhaps there is a way to avoid using the
  Axes class from axisartist in your use case. For example, could you
  import the Axes class as follows:
 
  from matplotlib.axes import Axes
 
  That seems to work with the Qt and PDF backends on Windows 7 (Anaconda
  Python).

 Hello Ryan,

 thanks for confirming the problem.  I've also seen that note, but I
 thought do not work means that the methods raise an exception, not
 that they arbitrarily ignore arguments :(

 While the standard Axis class works for the cut-down example I posted,
 it does not for what I'm trying to achieve (having a second x axis below
 the main one).  I came up with that solution following the matplotlib
 documentation:


 http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axisartist-with-parasiteaxes

 however I don't really understand why some of the contortions there are
 necessary (they are not explained in the documentation).

 Cheers,
 Daniele



 --
 Android is increasing in popularity, but the open development platform that
 developers love is also attractive to malware creators. Download this white
 paper to learn more about secure code signing practices that can help keep
 Android apps secure.
 http://pubads.g.doubleclick.net/gampad/clk?id=65839951iu=/4140/ostg.clktrk
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

--
Android is increasing in popularity, but the open development platform that
developers love is also attractive to malware creators. Download this white
paper to learn more about secure code signing practices that can help keep
Android apps secure.
http://pubads.g.doubleclick.net/gampad/clk?id=65839951iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Setting the tick label font size

2013-10-28 Thread Ryan Nelson
Daniele,

I noticed the same problem with the Qt backend. However, I was looking at
the documentation on the AxesGrid webpage here:
http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html
And I see the following warning:

axes_grid and axisartist (but not axes_grid1) uses a custom Axes class
(derived from the mpl’s original Axes class). As a side effect, some
commands (mostly tick-related) do not work. Use axes_grid1 to avoid this,
or see how things are different in axes_grid and axisartist (LINK needed)

Unfortunately, no link. But perhaps there is a way to avoid using the Axes
class from axisartist in your use case. For example, could you import the
Axes class as follows:

from matplotlib.axes import Axes

That seems to work with the Qt and PDF backends on Windows 7 (Anaconda
Python).

Ryan


On Mon, Oct 28, 2013 at 7:37 PM, Daniele Nicolodi dani...@grinta.netwrote:

 On 29/10/2013 00:17, Sterling Smith wrote:
  While your example tries to be self contained, which is great!, there is
 no difference between these two conditions...
 
  if BUG:
 ax1 = host_subplot(111, axes_class=Axes)
  else:
 ax1 = host_subplot(111, axes_class=Axes)

 Ops, obvious mistake. It should read:

 BUG = True
 if BUG:
 ax1 = host_subplot(111 , axes_class=Axes)
 else:
 ax1 = host_subplot(111)


 Cheers,
 Daniele



 --
 Android is increasing in popularity, but the open development platform that
 developers love is also attractive to malware creators. Download this white
 paper to learn more about secure code signing practices that can help keep
 Android apps secure.
 http://pubads.g.doubleclick.net/gampad/clk?id=65839951iu=/4140/ostg.clktrk
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

--
Android is increasing in popularity, but the open development platform that
developers love is also attractive to malware creators. Download this white
paper to learn more about secure code signing practices that can help keep
Android apps secure.
http://pubads.g.doubleclick.net/gampad/clk?id=65839951iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Plot Scatter plot with hist() method output

2013-08-19 Thread Ryan Nelson
Dilpreet,

Fortunately, you have a couple of options here. First of all, when you call
the plt.hist function, it actually returns three useful sets of data: the
frequencies, bin edges, and the bar patches. The first two are probably
what you want. You can grab those for later use in your code by doing the
following:

freq, bins, bars = plt.hist(data,histtype='bar',bins = 100,log=True)

It will be a little tricky here because the 'bins' array are the edges of
the bins that contain the frequency values, so there will be one more value
than the 'freq' array. You can quickly calculate the center of the bins by
taking the average of each bin pair:

(bins[1:] + bins[:-1])/2.

Alternatively, if you don't want to actually plot the histogram but just
the freq and bins arrays, then you can use the 'histogram' function in
Numpy, which I believe is used internally by Matplotlib.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html

Ryan


On Mon, Aug 19, 2013 at 7:27 PM, dilpreet singh giggs...@gmail.com wrote:

 Hi

 i want to plot a scatter plot similar to the one attached with email . I
 can plot a histogram but the hist method can't plot a scatter plot . Is
 there a way to use the output of the hist() method and use it as an input
 to the scatter plot ?

 The part of the code i am using to plot histogram is as follows :

 data = get_data()
 plt.figure(figsize=(7,4))
 ax = plt.subplots()
 plt.hist(data,histtype='bar',bins = 100,log=True)
 plt.show()

 Thanks
 Dilpreet



 --
 Introducing Performance Central, a new site from SourceForge and
 AppDynamics. Performance Central is your source for news, insights,
 analysis and resources for efficient Application Performance Management.
 Visit us today!
 http://pubads.g.doubleclick.net/gampad/clk?id=48897511iu=/4140/ostg.clktrk
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
Introducing Performance Central, a new site from SourceForge and 
AppDynamics. Performance Central is your source for news, insights, 
analysis and resources for efficient Application Performance Management. 
Visit us today!
http://pubads.g.doubleclick.net/gampad/clk?id=48897511iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Plot/save line collection object without margins

2013-07-06 Thread Ryan Nelson
You might need to explicitly specify your axes object rather than 
relying on plt.subplot.
Try replacing 'ax = plt.sublplot(111)' with 'ax = plt.axes([0, 0, 1, 1])'.
Ryan

On 7/5/2013 12:44 PM, death jun wrote:
 Hello list,

 I have LineCollection object: l = matplotlib.collections.LineCollection() 
 which I want to save as image without any kind of margins.

 What have I tried is following:

 ax = plt.subplot(111)
 ax.set_axis_off()
 ax.add_collection(l)
 ax.autoscale_view()
 plt.savefig('img.png')

 but there are still unwanted margins.

 How to plot without margins?


 Thanks

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

 Build for Windows Store.

 http://p.sf.net/sfu/windows-dev2dev
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


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

Build for Windows Store.

http://p.sf.net/sfu/windows-dev2dev
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Individual custom markers and colorbar

2013-04-26 Thread Ryan Nelson
Hackstein,

Francesco's suggestion works for me.
col.set_edgecolor( 'none' )

You can also set the linewidth to be 0.
col.set_linewidth( 0 )

Colorbars in these cases can be more painful than you might like. You 
need to make a mappable object and pass that into a figure.colorbar 
call. Rather than try to explain it in detail, I've just pasted a 
modified version of my first script that should do what you need.

Glad we're getting closer.

Ryan



import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection

n = 100

# Get your xy data points, which are the centers of the rectangles.
xy = np.random.rand(n,2)

# Set a fixed height
height = 0.02
# The variable widths of the rectangles
widths = np.random.rand(n)*0.1

# Get a color map and make some colors
cmap = plt.cm.hsv
colors = np.random.rand(n)*10.
# Make a normalized array of colors
colors_norm = colors/colors.max()
# Here's where you have to make a ScalarMappable with the colormap
mappable = plt.cm.ScalarMappable(cmap=cmap)
# Give it your non-normalized color data
mappable.set_array(colors)

rects = []
for p, w in zip(xy, widths):
 xpos = p[0] - w/2 # The x position will be half the width from the 
center
 ypos = p[1] - height/2 # same for the y position, but with height
 rect = Rectangle( (xpos, ypos), w, height ) # Create a rectangle
 rects.append(rect) # Add the rectangle patch to our list

# Create a collection from the rectangles
col = PatchCollection(rects)
# set the alpha for all rectangles
col.set_alpha(0.3)
# Set the colors using the colormap
col.set_facecolor( cmap(colors_norm) )
# No lines
col.set_linewidth( 0 )
#col.set_edgecolor( 'none' )

# Make a figure and add the collection to the axis.
fig = plt.figure()
ax = fig.add_subplot(111)
ax.add_collection(col)
# Add your ScalarMappable to a figure colorbar
fig.colorbar(mappable)
plt.show()



On 4/26/2013 7:15 AM, Hackstein wrote:
 Thanks, Ryan, this is (amost) exactly what I was looking  for. Now, I get the 
 markers and their colors right, but I still have two problems:
 The markers have a black edges, that I cannot get rid of. I've tried

 rect = Rectangle(..., ec=None)

 and also

 col.set=edgecolor(None)

 and 'None', respectively, both with no effect whatsoever.

 The second problem is, that I cannot get the colorbar to work.
 I tried

 sc = ax.add_collection(col)
 plt.colorbar(sc)

 and

 plt.colobar(col)

 both do not work.
 Any Ideas how to fix those two issues?

 Thanks,

 -Hackstein


 Message: 4
 Date: Thu, 25 Apr 2013 19:44:23 -0400
 From: Ryan Nelson rnelsonc...@gmail.com
 Subject: Re: [Matplotlib-users] Individual custom markers and colorbar
 To: matplotlib-users@lists.sourceforge.net
 Message-ID: 5179bfd7.7060...@gmail.com
 Content-Type: text/plain; charset=iso-8859-1

 Hackstein,

 Unfortunately, I'm not sure of an 'elegant' way to do what your asking
 with a single call to scatter. Others may know a better way. However,
 you can use rectangle patches and patch collections. (Requires a bit
 more code than scatter but is ultimately more flexible.)

 I think the example below does what you need, but with random numbers.

 Hope it helps a little.

 Ryan

 ###
 import numpy as np
 import matplotlib.pyplot as plt
 from matplotlib.patches import Rectangle
 from matplotlib.collections import PatchCollection

 n = 100

 # Get your xy data points, which are the centers of the rectangles.
 xy = np.random.rand(n,2)

 # Set a fixed height
 height = 0.02
 # The variable widths of the rectangles
 widths = np.random.rand(n)*0.1

 # Get a color map and color values (normalized between 0 and 1)
 cmap = plt.cm.jet
 colors = np.random.rand(n)

 rects = []
 for p, w, c in zip(xy, widths, colors):
  xpos = p[0] - w/2 # The x position will be half the width from the
 center
  ypos = p[1] - height/2 # same for the y position, but with height
  rect = Rectangle( (xpos, ypos), w, height ) # Create a rectangle
  rects.append(rect) # Add the rectangle patch to our list

 # Create a collection from the rectangles
 col = PatchCollection(rects)
 # set the alpha for all rectangles
 col.set_alpha(0.3)
 # Set the colors using the colormap
 col.set_facecolor( cmap(colors) )

 # Make a figure and add the collection to the axis.
 ax = plt.subplot(111)
 ax.add_collection(col)
 plt.show()

 ###


 On 4/24/2013 5:35 PM, Hackstein wrote:
 Hi all,

 I am trying to get a scatter plot using a colormap. Additionally, I
 need to define every marker for every data point individually -- each
 being a rectangle with fixed height but varying width as a function of
 the y-value. X and y being the data coordinates, z being a number to
 be color coded with the colormap.

 Ideally, I would like to create a list of width and height values for
 each data point and tell the scatter plot to use those.

 So far I got

Re: [Matplotlib-users] Individual custom markers and colorbar

2013-04-25 Thread Ryan Nelson

Hackstein,

Unfortunately, I'm not sure of an 'elegant' way to do what your asking 
with a single call to scatter. Others may know a better way. However, 
you can use rectangle patches and patch collections. (Requires a bit 
more code than scatter but is ultimately more flexible.)


I think the example below does what you need, but with random numbers.

Hope it helps a little.

Ryan

###
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection

n = 100

# Get your xy data points, which are the centers of the rectangles.
xy = np.random.rand(n,2)

# Set a fixed height
height = 0.02
# The variable widths of the rectangles
widths = np.random.rand(n)*0.1

# Get a color map and color values (normalized between 0 and 1)
cmap = plt.cm.jet
colors = np.random.rand(n)

rects = []
for p, w, c in zip(xy, widths, colors):
xpos = p[0] - w/2 # The x position will be half the width from the 
center

ypos = p[1] - height/2 # same for the y position, but with height
rect = Rectangle( (xpos, ypos), w, height ) # Create a rectangle
rects.append(rect) # Add the rectangle patch to our list

# Create a collection from the rectangles
col = PatchCollection(rects)
# set the alpha for all rectangles
col.set_alpha(0.3)
# Set the colors using the colormap
col.set_facecolor( cmap(colors) )

# Make a figure and add the collection to the axis.
ax = plt.subplot(111)
ax.add_collection(col)
plt.show()

###


On 4/24/2013 5:35 PM, Hackstein wrote:


Hi all,

I am trying to get a scatter plot using a colormap. Additionally, I 
need to define every marker for every data point individually -- each 
being a rectangle with fixed height but varying width as a function of 
the y-value. X and y being the data coordinates, z being a number to 
be color coded with the colormap.


Ideally, I would like to create a list of width and height values for 
each data point and tell the scatter plot to use those.


So far I got colormapped data with custom markers (simplified):

[code]

import numpy as np

import matplotlib.pyplot as plt

from pylab import *

x = y = [1,2,3,4,5]

z = [2,4,6,8,10]

colors = cm.gnuplot2

verts_vec = list(zip([-10.,10.,10.,-10.],[-5.,-5.,5.,5.]))

fig = plt.figure(1, figsize=(14.40, 9.00))

ax = fig.add_subplot(1,1,1)

sc = ax.scatter(x, y, c=np.asarray(z), marker=None, edgecolor='None', 
verts=verts_vec, cmap=colors, alpha=1.)


plt.colorbar(sc, orientation='horizontal')

plt.savefig('test.png', dpi=200)

plt.close(1)

[/code]

But I need to define a marker size for each point, and I also need to 
do that in axis scale values, not in points.


I imagine giving verts a list of N*2 tuples instead of 2 tuples, N 
being len(x), to define N individual markers.


But when doing that I get the error that vertices.ndim==2.

A less elegant way would be to plot every data point in an individual 
scatter plot function, using a for-loop iterating over all data 
points. Then, however, I see no way to apply a colormap and colorbar.


What is the best way to accomplish that then?

Thanks,

-Hackstein



--
Try New Relic Now  We'll Send You this Cool Shirt
New Relic is the only SaaS-based application performance monitoring service
that delivers powerful full stack analytics. Optimize and monitor your
browser, app,  servers with just a few lines of code. Try New Relic
and get this awesome Nerd Life shirt! http://p.sf.net/sfu/newrelic_d2d_apr


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


--
Try New Relic Now  We'll Send You this Cool Shirt
New Relic is the only SaaS-based application performance monitoring service 
that delivers powerful full stack analytics. Optimize and monitor your
browser, app,  servers with just a few lines of code. Try New Relic
and get this awesome Nerd Life shirt! http://p.sf.net/sfu/newrelic_d2d_apr___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Impossible to draw a direction of arrows in Matplotlib???

2013-04-12 Thread Ryan Nelson
I'm not sure that I understand exactly what you are trying to do, but 
you may want to look into Matplotlib annotation. Here's a really quick 
example:


import matplotlib.pyplot as plt
plt.annotate('', (1, 1), (0, 0),
arrowprops=dict(facecolor='black'))
plt.axis([-1, 2, -1, 2])
plt.show()

There are many options to make very fancy arrows, and there are several 
places in the docs to read about this in more detail:

http://matplotlib.org/users/annotations_intro.html
http://matplotlib.org/users/annotations_guide.html

Hope that helps a little. Good luck.

Ryan

On 4/12/2013 5:55 AM, Bakhtiyor Zokhidov wrote:

Hi,
I have encountered some problem while I was drawing a direction of
arrow. I have point (x,y) coordinates and angle of them. What I want to
do is that to draw arrow according to the given angle (just to show the
point direction as an arrow in each point coordinate). Here, we should
assume coordinates of '+x', '+y', '-x ', '-y' are 90, 0, 270, 180
degrees, respectively.
I am a bit unfamiliar with Python drawing tools. I am still not sure to
draw directional point (arrow based on angle) whether I use pylab or
some other modules or.. still not sure at all. I put the following codes
as a sample to give better description:

import numpy as np
import scipy as sp
import pylab as pl


def draw_line(x,y,angle):
 # Inputs:
 x = np.array([ 2, 4, 8, 10, 12, 14, 16])
y = np.array([ 5, 10, 15, 20, 25, 30, 35])
angles = np.array([45,275,190,100,280,18,45])

# First, draw (x,y) coordinate
???
# Second, according to the angle indicate the direction as
an arrow
???

Thanks in advance for your friendly support,


--
Precog is a next-generation analytics platform capable of advanced
analytics on semi-structured data. The platform includes APIs for building
apps and a phenomenal toolset for data science. Developers can use
our toolset for easy data analysis  visualization. Get a free account!
http://www2.precog.com/precogplatform/slashdotnewsletter


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


--
Precog is a next-generation analytics platform capable of advanced
analytics on semi-structured data. The platform includes APIs for building
apps and a phenomenal toolset for data science. Developers can use
our toolset for easy data analysis  visualization. Get a free account!
http://www2.precog.com/precogplatform/slashdotnewsletter___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Unicode characters in PS output

2013-02-25 Thread Ryan Nelson

On 2/25/2013 9:29 PM, Gökhan Sever wrote:

Hello,

For some reason, I can't get the degree sign showing up in my ps output:

Here is the simple test code:

fp = plt.figure(figsize=(8.5, 11))
fp.text(0.5, 0.5, uTemperature, ^(0)C, color='black', fontsize=16)
plt.savefig('test.ps http://test.ps', papertype='letter')
plt.savefig('test.pdf', papertype='letter')

PS output shows Temperature, ?C, however PDF renders degree sign 
correctly.


I can't seem to select the text in PS output, but the text is 
selectable in PDF.


This is probably a font issue, where PDF uses DejaVu, on the other 
hand PS uses a Times type font.


So, how can I adjust matplotlib to save in PS file?

Thanks.

--
Gökhan


--
Everyone hates slow websites. So do we.
Make your web apps faster with AppDynamics
Download AppDynamics Lite for free today:
http://p.sf.net/sfu/appdyn_d2d_feb


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

Gökhan,

I tried your code, and everything worked fine for me. (PythonXY 2.7.3.1 
on Windows 7)
However, I usually use the escaped unicode value rather than unicode 
characters directly. Does the following work instead:


fp = plt.figure(figsize=(8.5, 11))
fp.text(0.5, 0.5, uTemperature, \u00B0C, color='black', fontsize=16)
plt.savefig('test.ps http://test.ps', papertype='letter')
plt.savefig('test.pdf', papertype='letter')

Just a thought. Hope it helps.

Ryan


--
Everyone hates slow websites. So do we.
Make your web apps faster with AppDynamics
Download AppDynamics Lite for free today:
http://p.sf.net/sfu/appdyn_d2d_feb___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] fading line plot

2013-02-24 Thread Ryan Nelson
On 2/24/2013 1:28 PM, Paul Anton Letnes wrote:
 Hi everyone,

 I've been looking into making an animation of a mechanical system. In its 
 first incarnation, my plan was as follows:
 1) Make a fading line plot of two variables (say, x and y)
 2) Run a series of such plots through ffmpeg/avencode to generate an animation

 First, I'm wondering whether there's a built-in way of making a fading line 
 plot, i.e. a plot where one end of the line is plotted with high alpha, the 
 other end with low alpha, and intermediate line segments with linearly scaled 
 alpha. For now, I've done this by manually chunking the x and y arrays and 
 plotting each chunk with different alpha. Is there a better way? Is there 
 interest in creating such a plotting function and adding it to matplotlib?

 Second, is there a way of integrating the chunked generation of fading 
 lines with the animation generating features of matplotlib? It seems 
 possible, although a bit clunky, at present, but maybe someone has a better 
 idea at what overall approach to take than I do.

 Cheers
 Paul
 --
 Everyone hates slow websites. So do we.
 Make your web apps faster with AppDynamics
 Download AppDynamics Lite for free today:
 http://p.sf.net/sfu/appdyn_d2d_feb
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

Paul,

I've had to do something similar to what you need, and I found the 
following example from the Gallery quite helpful:
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
I think the second plot in particular is pretty close to what you want; 
however, you'll need to set the alpha values manually. This is what I've 
done for line collections, scatter plots, etc.
_
import numpy as np
import matplotlib.pyplot as plt

norm_data = np.random.rand(20)
xs = np.random.rand(20)

# Pick a colormap and generate the color array for your data
cmap = plt.cm.spectral
colors = cmap(norm_data)
# Reset the alpha data using your desired values
colors[:,3] = norm_data

# Adding a colorbar is a bit of a pain here, need to use a mappable
fig = plt.figure()
plt.scatter(xs, norm_data, c=colors, s=55)
mappable = plt.cm.ScalarMappable(cmap=cmap)
mappable.set_array(norm_data)
fig.colorbar(mappable)
plt.show()
_

Hope that helps a little.

Ryan


--
Everyone hates slow websites. So do we.
Make your web apps faster with AppDynamics
Download AppDynamics Lite for free today:
http://p.sf.net/sfu/appdyn_d2d_feb
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] color pallette suggestions wanted

2012-10-12 Thread Ryan Nelson
Andreas,

Perhaps you would be better off making your own colormap considering that
your data is not symmetric around zero. You could do something like the
following:

--
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as plc

data = np.random.randn(12,72)
data = data*5. - 5.

zero =  -1*data.min()/(data.max() - data.min())

cdict = {'red':   [(0.0, 1.0, 1.0),
  (zero, 1.0, 1.0),
  (1.0, 0.0, 0.0)],
 'green': [(0.0, 0.0, 0.0),
  (zero, 1.0, 1.0),
  (1.0, 0.0, 0.0)],
 'blue':  [(0.0, 0.0, 0.0),
  (zero, 1.0, 1.0),
  (1.0, 1.0, 0.0)],
 }

cmap = plc.LinearSegmentedColormap('cmap', cdict, N=1000)
mappable = plt.cm.ScalarMappable(cmap=cmap)
mappable.set_array(data)

fig = plt.figure()
plt.pcolormesh(data, cmap=cmap)
fig.colorbar(mappable)

plt.show()
--

Of course, the zero calculation assumes that zero actually exists in your
data set. That can be fixed with a simple if...else statement if you want
this to be more robust.

You can get rid of a few lines from this code if you don't want to set a
ScalarMappable object. However, I was doing some stuff with line
collections where I wanted some colors to have an alpha associated with
them, and I found that I was losing that info with the simpler pyplot
interface for colorbar generation. So I left in the slightly more complex
code for reference. (This might be changed in newer versions of mpl, I just
haven't needed to rework my code to check.)

Ryan

On Fri, Oct 12, 2012 at 4:17 AM, Andreas Hilboll li...@hilboll.de wrote:

 Hi,

 I have some data I want to plot using pcolormesh. It's 2d climatological
 data, see the attached plot. My data is in a range from -7 to +0.6. I want
 to be 0.0 to be clearly visible, while at the same time, the color range
 should show the full dynamic of the values. I played with the bwr and
 seismic color maps, centering on zero, so that white is 0.0. However, I'm
 not too happy with the dynamic range I get in the negative.

 Any suggestions are very welcome ...

 Cheers, Andreas.

 --
 Don't let slow site performance ruin your business. Deploy New Relic APM
 Deploy New Relic app performance management and know exactly
 what is happening inside your Ruby, Python, PHP, Java, and .NET app
 Try New Relic at no cost today and get our sweet Data Nerd shirt too!
 http://p.sf.net/sfu/newrelic-dev2dev
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users


--
Don't let slow site performance ruin your business. Deploy New Relic APM
Deploy New Relic app performance management and know exactly
what is happening inside your Ruby, Python, PHP, Java, and .NET app
Try New Relic at no cost today and get our sweet Data Nerd shirt too!
http://p.sf.net/sfu/newrelic-dev2dev___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] please help with arrow drawing.

2011-10-18 Thread Ryan Nelson
As far as I know, the 'arrow' function is not recommended. The 'annotate'
function has a lot more features. Here's your code with the annotate
function:

import pylab
from scipy import optimize
import numpy
x1=numpy.arange(-4000,1000,0.1)
x2=numpy.arange(-1000,4000,0.1)
y1=100*numpy.square(x1+1500)
y2=100*numpy.square(x2-1500)-0.1e9
pylab.figure()
pylab.plot(x1,y1,x2,y2)
pylab.grid(True)
pylab.annotate('',(-3000,0),(-3000,-1),
arrowprops=dict(arrowstyle='-'))
pylab.xlim(-5000,5000)
pylab.ylim(-2e8,7e8)
pylab.show()

Hope that helps a little.

Ryan

On Mon, Oct 17, 2011 at 12:02 PM, Piter_ x.pi...@gmail.com wrote:

 Hi all
 I want to draw an two headed arrow between two points.
 But I get a line. What I am doing wrong? I actually try to plot an
 image similar to this one:

 http://upload.wikimedia.org/wikipedia/commons/a/a3/Parameters_of_the_Marcus_Equation.JPG
 may be I can use an annotate function for this.
 Thanks for help.
 Petro.
 
 import pylab
 from scipy import optimize
 import numpy
 x1=numpy.arange(-4000,1000,0.1)
 x2=numpy.arange(-1000,4000,0.1)
 y1=100*numpy.square(x1+1500)
 y2=100*numpy.square(x2-1500)-0.1e9
 pylab.figure()
 pylab.plot(x1,y1,x2,y2)
 pylab.grid(True)
 pylab.arrow(-3000,0,0,-1,width=1)
 pylab.xlim(-5000,5000)
 pylab.ylim(-2e8,7e8)
 pylab.show()
 ###x


 --
 All the data continuously generated in your IT infrastructure contains a
 definitive record of customers, application performance, security
 threats, fraudulent activity and more. Splunk takes this data and makes
 sense of it. Business sense. IT sense. Common sense.
 http://p.sf.net/sfu/splunk-d2d-oct
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

--
All the data continuously generated in your IT infrastructure contains a
definitive record of customers, application performance, security
threats, fraudulent activity and more. Splunk takes this data and makes
sense of it. Business sense. IT sense. Common sense.
http://p.sf.net/sfu/splunk-d2d-oct___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] color problems in scatter plot

2011-10-04 Thread Ryan Nelson
Mike,

You may want to look into the matplotlib.cm and matplotlib.colors modules.
I've had good success with matplotlib.colors.LinearSegmentedColormap and its
'from_list' method. The documentation is the best location for information
on this topic. If you have a large number of locations, then the color
differences will be pretty small, unless you use a colormap with lots of
different colors. Below is your example using the 'from_list' method and the
built-in colormap 'hsv' (you'll just have to flip around the comments). For
the matplotlib.cm colormaps, be sure to passed in normalized values (which
is why the call to the colormap is slightly complex).

Maybe this is a bit more help.

Ryan

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as plc
import matplotlib.cm as mcm

IDs = np.array([47, 33, 47, 12, 50, 50, 27, 27, 16, 27])
locations = np.array(['201', '207', '207', '205', '204', '201', '209',
'209', \
'207','207'])
dates = np.array([ 733315.83240741,  733315.83521991,  733315.83681713,
   733315.83788194,  76.54554398,  76.54731481,
   77.99842593,  77.99943287,  78.00070602,
   78.00252315])

fig = plt.figure()
ax = fig.add_subplot(111)
locs_un = np.unique(locations)
# The variable assignment below can be removed if you use the mcm module.
cs = plc.LinearSegmentedColormap.from_list('Colormap name', ['r', 'g', 'b'],
N=len(locs_un) )
for n, i in enumerate(locs_un):
# Reverse the comments here to use the mcm module 'hsv' colormap.
ax.plot(dates[locations==i],IDs[locations==i],'d', c=cs(n), label=i)
#ax.plot(dates[locations==i],IDs[locations==i],'d',
#   c=mcm.hsv( float(n)/(len(locs_un)-1) ), label=i)
ax.xaxis_date()
fig.autofmt_xdate()
plt.legend(numpoints=1)
plt.grid(True)
plt.show()


On Tue, Oct 4, 2011 at 5:25 PM, Michael Castleton fatuhe...@yahoo.comwrote:


 Ryan,
 I should clarify my color issue. Your code is smart enough to generate
 however many colors are needed but I want to make sure the colors are all
 unique.
 Thanks again!

 Mike



 Mike, sorry to send this twice... I should have sent it to the list as
 well...
 ___
 Mike,

 If your locations were integers or floats rather than strings, you could
 just change the scatter call to the following:
 ax.scatter(dates,IDs,c=
 locations,marker='d')
 I don't know about a legend... I don't know if that is possible with a
 scatter plot (?). Because scatter plots get their colors based off of a
 color map, you could generate a color bar for your data. You may need to
 capture the collection object returned from the scatter plot function call,
 though. Here's your code with these modifications:

 # Of course, you need to change your locations list to integers rather than
 strings.

 fig = plt.figure()
 ax = fig.add_subplot(111)
 sc = ax.scatter(dates,IDs,c=locations,marker='d')
 ax.xaxis_date()
 fig.autofmt_xdate()
 plt.colorbar(sc)
 plt.grid(True)
 plt.show()

 If you really need a legend, then you could do a loop of plot commands for
 each set of unique locations. Using some fancy Numpy masking makes the
 process easier...

 import numpy as np
 import matplotlib.pyplot as plt

 IDs = np.array([47, 33, 47, 12, 50, 50, 27, 27, 16, 27])
 locations = np.array(['201', '207', '207', '205', '204', '201', '209',
 '209', \
'207','207'])
 dates = np.array([ 733315.83240741,  733315.83521991,  733315.83681713,

   733315.83788194,  76.54554398,  76.54731481,
   77.99842593,  77.99943287,  78.00070602,
   78.00252315])


 fig = plt.figure()
 ax = fig.add_subplot(111)
 cs = ['r', 'b', 'g', 'k', 'c']
 for n, i in enumerate(np.unique(locations)):
ax.plot(dates[locations==i],IDs[locations==i],'d', c=cs[n%len(cs)],
 label=i)
 ax.xaxis_date()
 fig.autofmt_xdate()
 plt.legend(numpoints=1)
 plt.grid(True)
 plt.show()

 Not sure if this is exactly what you wanted, but I hope it helps a little.

 Ryan



 --
 View this message in context:
 http://old.nabble.com/color-problems-in-scatter-plot-tp32584727p32592799.html
 Sent from the matplotlib - users mailing list archive at Nabble.com.



 --
 All the data continuously generated in your IT infrastructure contains a
 definitive record of customers, application performance, security
 threats, fraudulent activity and more. Splunk takes this data and makes
 sense of it. Business sense. IT sense. Common sense.
 http://p.sf.net/sfu/splunk-d2dcopy1
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

--
All the data continuously generated in your IT infrastructure contains a
definitive record of customers, application performance, security
threats, fraudulent activity and 

Re: [Matplotlib-users] color problems in scatter plot

2011-10-03 Thread Ryan Nelson
Mike, sorry to send this twice... I should have sent it to the list as
well...
___
Mike,

If your locations were integers or floats rather than strings, you could
just change the scatter call to the following:
ax.scatter(dates,IDs,c=
locations,marker='d')
I don't know about a legend... I don't know if that is possible with a
scatter plot (?). Because scatter plots get their colors based off of a
color map, you could generate a color bar for your data. You may need to
capture the collection object returned from the scatter plot function call,
though. Here's your code with these modifications:

# Of course, you need to change your locations list to integers rather than
strings.

fig = plt.figure()
ax = fig.add_subplot(111)
sc = ax.scatter(dates,IDs,c=locations,marker='d')
ax.xaxis_date()
fig.autofmt_xdate()
plt.colorbar(sc)
plt.grid(True)
plt.show()

If you really need a legend, then you could do a loop of plot commands for
each set of unique locations. Using some fancy Numpy masking makes the
process easier...

import numpy as np
import matplotlib.pyplot as plt

IDs = np.array([47, 33, 47, 12, 50, 50, 27, 27, 16, 27])
locations = np.array(['201', '207', '207', '205', '204', '201', '209',
'209', \
'207','207'])
dates = np.array([ 733315.83240741,  733315.83521991,  733315.83681713,

   733315.83788194,  76.54554398,  76.54731481,
   77.99842593,  77.99943287,  78.00070602,
   78.00252315])


fig = plt.figure()
ax = fig.add_subplot(111)
cs = ['r', 'b', 'g', 'k', 'c']
for n, i in enumerate(np.unique(locations)):
ax.plot(dates[locations==i],IDs[locations==i],'d', c=cs[n%len(cs)],
label=i)
ax.xaxis_date()
fig.autofmt_xdate()
plt.legend(numpoints=1)
plt.grid(True)
plt.show()

Not sure if this is exactly what you wanted, but I hope it helps a little.

Ryan


On Mon, Oct 3, 2011 at 2:49 PM, Michael Castleton fatuhe...@yahoo.comwrote:


 Hello,
 I am using Matplotlib 1.0.0 in Python 2.6.
 I am trying to plot time series data of unique IDs and color the points
 based on location. Each data point has a unique ID value, a date value, and
 a location value.
 The unique IDs and date values are plotting fine but I am unable to control
 the color and subsequently the legend.

 Here is a sample of the data.
 IDs = [47, 33, 47, 12, 50, 50, 27, 27, 16, 27]
 locations = ['201', '207', '207', '205', '204', '201', '209', '209',
 '207','207']
 dates = [ 733315.83240741,  733315.83521991,  733315.83681713,
733315.83788194,  76.54554398,  76.54731481,
77.99842593,  77.99943287,  78.00070602,
78.00252315]

 This basic code works.

 fig = plt.figure()
 ax = fig.add_subplot(111)
 ax.scatter(dates,IDs,marker='d')
 ax.xaxis_date()
 fig.autofmt_xdate()
 plt.grid(True)
 plt.show()

 I've been trying to figure out how to set color = locations with no
 success.
 Any ideas out there?
 Thanks,

 Mike
 --
 View this message in context:
 http://old.nabble.com/color-problems-in-scatter-plot-tp32584727p32584727.html
 Sent from the matplotlib - users mailing list archive at Nabble.com.



 --
 All the data continuously generated in your IT infrastructure contains a
 definitive record of customers, application performance, security
 threats, fraudulent activity and more. Splunk takes this data and makes
 sense of it. Business sense. IT sense. Common sense.
 http://p.sf.net/sfu/splunk-d2dcopy1
 ___
 Matplotlib-users mailing list
 Matplotlib-users@lists.sourceforge.net
 https://lists.sourceforge.net/lists/listinfo/matplotlib-users

--
All the data continuously generated in your IT infrastructure contains a
definitive record of customers, application performance, security
threats, fraudulent activity and more. Splunk takes this data and makes
sense of it. Business sense. IT sense. Common sense.
http://p.sf.net/sfu/splunk-d2dcopy1___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] order of plotting for 'layer' of data

2011-09-04 Thread Ryan Nelson
Rob,

Have you tried the zorder argument. It is an integer that controls the
relative 'height' of a plotting element: higher numbers are plotted over
lower numbers. For example, the following code plots the scatter points on
top of the plotted line (even though scatter was called first):

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1, 1, 10)
y = np.random.rand(10)

plt.scatter(x, y, s=50, zorder=2)
plt.plot(x, y, 'r', lw=2, zorder=1)
plt.show()

Also, looking over your code, I noticed you had a for loop for your plot
commands. The plot command can take two dimensional arrays for x and y as
well. In this case, the x and y data for each individual plot are the
columns of the 2D arrays. For your problem in particular, you may find
Numpy's 'tile' command to be useful as well. Here's some code that does
something similar to what you are doing (I think).

import numpy as np
import matplotlib.pyplot as plt

z = np.tile( range(5), (5,1) )
plt.plot(z, np.random.rand(5, 5), 'o')
plt.show()

This may not make a big difference in your code, but if you have a lot of
data, it may speed things up a little. (As I understand it, the Python for
loops can be a little slow.)

Hope this helps a little.

Ryan


Date: Fri, 02 Sep 2011 14:18:39 -0230
 From: Rob Briggs rdbri...@mun.ca
 Subject: [Matplotlib-users] order of plotting for 'layer' of data
 To: matplotlib-users@lists.sourceforge.net
 Message-ID: 1314982119.4902.118.camel@localhost.localdomain
 Content-Type: text/plain; charset=us-ascii

 Hello,

 I'm not sure of the correct way to ask this question.I'm trying to
 create a plot that has a number of layers. I plot a standard plot, then
 a scatterplot over that. See attachment. I expected the scatter plot to
 'render/draw' after the standard plot command, but the scatter plot data
 is buried under the standard command.

 I tried changing the order, i.e. scatterplot first but that had no
 effect. How do I ensure the scatterplot data is plotted above/over the
 other data?

 The following code extract is after all the data has been read and
 sorted.

 # start plotting
 plt.close()

 # first EAIS data
 stitle = 'plot showing cumulative paleoHmodel and paleoHscore for EAIS'
 # set up index range for plotting
 il=0  # index for lower bound to plot
 iu=idx_splt   # index for upper bound to plot

 fig = plt.figure(5,figsize=(18,12))
 ax1 = fig.add_subplot(111)
 plt.title(stitle, fontsize=16)
 plt.xlabel(paleoH data point)
 plt.ylabel(thickness [m])

 ii=np.empty(num_rows)
 # plot the model results
 for i in range(il,iu):
ii[:] = i+1
plt.plot(ii,a[:,i],'o',color='0.9')

 # set axis limits
 ymin=-1800
 ymin=-500
 ax1.set_xlim(il,iu+1)
 top   = 3000
 bottom=-500
 ax1.set_ylim(bottom, top)

 # plot the labels
 for i in range(il,iu):
plt.text(i+1,ymin,datn[i], horizontalalignment='center',
 fontsize=10,rotation='vertical', verticalalignment='bottom')


 #cmap = cm.get_cmap('PRGn', 10)
 #cmap = cm.get_cmap('autumn_r', 100)
 #cmap = cm.get_cmap('gray', 100)

 #plt.scatter(obs[il:iu,0],obs[il:iu,1],c=time[il:iu],marker='s',s=50,cmap=cmap)
 plt.scatter(obs[il:iu,0], obs[il:iu,1], c=time[il:iu],marker='s',s=100)
 plt.colorbar()

 # plot the observation dp with error bars
 #plt.errorbar(obs[il:iu,0], obs[il:iu,1], yerr=obs[il:iu,2], fmt='r.')

 plt.grid(which='both')
 fname=scoreVSpaleoHsite.png
 plt.savefig(fname)
 plt.show()


 Regards

 Rob


 This electronic communication is governed by the terms and conditions at
 http://www.mun.ca/cc/policies/electronic_communications_disclaimer_2011.php
 -- next part --
 A non-text attachment was scrubbed...
 Name: scoreVSpaleoHsite.png
 Type: image/png
 Size: 223292 bytes
 Desc: not available


--
Special Offer -- Download ArcSight Logger for FREE!
Finally, a world-class log management solution at an even better 
price-free! And you'll get a free Love Thy Logs t-shirt when you
download Logger. Secure your free ArcSight Logger TODAY!
http://p.sf.net/sfu/arcsisghtdev2dev___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] Unexpected behavior with axes.twinx + pyplot.xticks

2011-09-04 Thread Ryan Nelson
Hello all,

I noticed some unusual behavior with specific combinations of axes.twinx and
pyplot.xticks. It seems that under certain conditions, the pyplot.xticks
command can cause an x offset of the plots. Here's a relatively short
example (as written, this works fine):

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-np.pi, np.pi, 1000)

fig = plt.figure()
ax1 = plt.axes()
ax1.plot(x, np.sin(x)+1)
plt.ylim(-1,2)

ax2 = ax1.twinx()
ax2.plot(x, np.sin(x) )
plt.ylim(-1,2)

plt.xlim(-np.pi, np.pi)
ts = np.linspace(-1, 3, 5)
#ts = np.linspace(-1, 4, 5)
plt.xticks( ts, ['%.2f'%i for i in ts] )

plt.show()

However, if the comment on the 'ts' array creation code is reversed, the
second plot appears offset from the original.

I realize it is idiotic to put ticks outside the axis range, but this caused
some problems when I inadvertently did it once (or more...).

I've tried this with Matplotlib 1.0.1/Python 2.6.6 (Python x,y) on Windows 7
and Matplotlib 1.0.1/Python 2.7.1 on Gentoo Linux.

Thanks

Ryan
--
Special Offer -- Download ArcSight Logger for FREE!
Finally, a world-class log management solution at an even better 
price-free! And you'll get a free Love Thy Logs t-shirt when you
download Logger. Secure your free ArcSight Logger TODAY!
http://p.sf.net/sfu/arcsisghtdev2dev___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] How do you Plot data generated by a python script?

2011-08-25 Thread Ryan Nelson
If I understand your question correctly, I may have a solution to your
problem. First of all, the statement below, when converted to Python
code, will generate an array of numbers the same length of your masses list.
 'y runs fron 0 to n where n == len(masses) '
However, this statement will give you a single number:
 x = 'mass_avg = sum(masses)/len(masses)'
You will not be able to plot these two objects because of the different
sizes. If you are asking about a 'running' or cumulative mean, then you may
want to use the cumulative sum function from Numpy (cumsum). To convert this
into a cumulative average, you can do a simple division.

Below is a modification to your script that incorporates this averaging
technique. (I don't know why you want to print everything. Surely you can't
see all of the data as the file gets processed. It is also a very slow
operation... I'll just ignore those parts.)

import numpy as np
import matplotlib.pyplot as plt
f = open('myfile.txt')
f.next()# You want to skip the first line, I guess.
mass = []
for line in f:
# This will skip the lines that are spaces.
if line.isspace(): continue
# The strip function is unnecessary. The defalut for the split function
takes care of that.
columns = line.split()
# Don't call the float function every time. It's a waste.
mass.append( columns[8] )
# Here we can convert the list of strings into an array of floats with the
dtype keyword.
mass = np.array( mass, dtype='float')
# Here's the cumulative average steps.
mass_sum = np.cumsum(mass)
mass_average = mass_sum/ np.arange(1, len(mass_sum) + 1)
# If you only plot one array or list of values, they are assumed to be the y
values.
# The x values in that case are the indices of the y value array.
plt.plot(mass_average)
plt.show()


Ryan


 Message: 5
 Date: Thu, 25 Aug 2011 11:15:57 -0700 (PDT)
 From: surfcast23 surfcas...@gmail.com
 Subject: Re: [Matplotlib-users] How do you Plot data generated by a
python script?
 To: matplotlib-users@lists.sourceforge.net
 Message-ID: 32336570.p...@talk.nabble.com
 Content-Type: text/plain; charset=us-ascii


 Hi Martin,

 Thank for the relpy.  What I have is a script that reads the data from
 a large file then prints out the values listed in a particular column. What
 I now need to do is have the information in that column plotted as the
 number of rows vs. the mean value of all of the rows. What I have so far is

 import matplotlib.pyplot as plt

 masses = []

 f = open( 'myfile.txt','r')
 f.readline()
 for line in f:
  if line != ' ':
line = line.strip()  # Strips end of line character
columns = line.split()# Splits into coloumn
mass = columns[8]  # Column which contains mass values
mass = float(mass)
masses.append(mass)
print(mass)

 plt.plot()
 plt.show


 I am thinking I can do something like

 'y runs fron 0 to n where n == len(masses) '
 x = 'mass_avg = sum(masses)/len(masses)'

 Problem is I don' tknow how to have matplotlib do it with out giving me an
 error about dimentions. I would also like to do this with out having to
 write and read from another file. I alos need to to be able to work on
 files
 with ddifering numbers of rows.

 Thanks





 mdekauwe wrote:
 
  I wasn't quite able to follow exactly what you wanted to do but maybe
 this
  will help. I am going to generate some data that I think sounds a bit
  like yours, write it to a file, clearly you already have this. Then I am
  going to read it back in and plot it, e.g.
 
  import matplotlib.pyplot as plt
  import numpy as np
 
  # Generate some data a little like yours, I think?
  # print it to a file, i.e. I am making your myfile.txt
  numrows = 100
  numcols = 8
  mass = np.random.normal(0, 1, (numrows  * numcols)).reshape(numrows,
  numcols)
  f = open(myfile.txt, w)
  for i in xrange(numrows):
  for j in xrange(numcols):
  print f,  mass[i,j],
  print  f
  f.close()
 
  # read the file back in
  mass = np.loadtxt(myfile.txt)
 
  # plot the 8th column
  fig = plt.figure()
  ax = fig.add_subplot(111)
  ax.plot(mass[:,7], 'r-o')
  ax.set_xlabel(Time)
  ax.set_ylabel(Mass)
  plt.show()
 
 
  I wasn't clear on the mean bit, but that is easy to do with numpy, e.g.
 
  mean_mass = np.mean(mass[:,8])
 
  etc.
 
  Numpy et al is great for stuff like this.
 
  Hope that helps,
 
  Martin
 
 

 --
 View this message in context:
 http://old.nabble.com/How-do-you-Plot-data-generated-by-a-python-script--tp32328822p32336570.html
 Sent from the matplotlib - users mailing list archive at Nabble.com.


--
EMC VNX: the world's simplest storage, starting under $10K
The only unified storage solution that offers unified management 
Up to 160% more powerful than alternatives and 25% more efficient. 
Guaranteed. http://p.sf.net/sfu/emc-vnx-dev2dev___
Matplotlib-users mailing list

[Matplotlib-users] Unusual (?) spacing with sub-/superscripts

2011-01-16 Thread Ryan Nelson
Hello everyone,

I frequently use subscripts and superscripts in text on my plots, but 
I've noticed that the line and character spacing (kerning ?) is not 
always as I would expect. For most things, this is not a problem. 
However, I would occasionally like various text objects to line up with 
one another, and at these times, this spacing difference can become a issue.

I guess I have a couple questions at this point... First, is this 
expected? Second, is there any (simple) way I can control the line and 
character spacing? I see there is a 'linespacing' keyword argument; 
however, this seems to be a multiplier relative to the total text height 
for each line not an absolute, fixed height of every line. For character 
spacing, is there a special symbol I could insert to add or removing 
spacing between characters?

I'm using Matploblib 1.0.0 that ships with Python(x,y) for Windows. 
Below is a test script that highlights these differences (at least on my 
system).

Any help or suggestions are most appreciated. (I don't know much TeX, so 
I appologize if these differences are obvious for those in the know.)

Ryan

import matplotlib.pyplot as plt
plt.rc('font', size=25.0)
plt.text(0.25, 0.25,
 'X1Y2\nX1Y2\nX$_1$Y$_2$\nX$_{1}$Y$_{2}$\n$X_1Y_2$\n$X_{1}Y_{2}$')
plt.text(0.75, 0.25,
 'X1Y2\nX1Y2\nX$^1$Y$^2$\nX$^{1}$Y$^{2}$\n$X^1Y^2$\n$X^{1}Y^{2}$')
plt.text(0.5, 0.25, 'X$_{1}$Y$_{2}$\nX$^{1}$Y$^{2}$\n$X_1Y_2$\n$X^1Y^2$')
plt.show()


--
Protect Your Site and Customers from Malware Attacks
Learn about various malware tactics and how to avoid them. Understand 
malware threats, the impact they can have on your business, and how you 
can protect your company and customers by using code signing.
http://p.sf.net/sfu/oracle-sfdevnl
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users