[Matplotlib-users] Clipping a plot inside a polygon
Hi all,
I want to be able to plot data on maps (using basemap or cartopy) inside
specific regions, eg a single state, province or country. A similar
question was asked a long time ago on the mailing list and the suggested
solution back then was to read the bounding polygon from a shapefile and
then check if each individual point was inside that polygon. Currently I
have no problem doing this if I use matplotlib.path.Path.contains_points()
to mask the original data array, but the disadvantage to this solution is
that it is very slow. Another solution that I have discovered recently is
to use the set_clip_path() method for artists. In addition to being much
faster, this also makes the areas near the polygon boundary look much
smoother since the actual items being clipped are individual pixels and not
data points.
Here is an example script that plots an image via imshow, but the only part
of the image that gets shown is inside the hexagon.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import RegularPolygon
data = np.arange(100).reshape(10, 10)
fig = plt.figure()
ax = fig.add_subplot(111)
im = ax.imshow(data)
poly = RegularPolygon([ 0.5, 0.5], 6, 0.4, fc='none',
ec='k', transform=ax.transAxes)
im.set_clip_path(poly)
ax.add_patch(poly)
ax.axis('off')
plt.show()
While this does seem like an ideal solution, it doesn't work for every type
of plot. The most notable example is contourf(). It returns a
QuadContourSet instance which does not inherit from Artist, so it does not
contain the set_clip_path() method. My main question is whether there is a
mechanism in matplotlib that can convert something like a QuadContourSet
into an image so I can make use of this solution for contourf() as well. Or
better yet, is there perhaps another artist within the axes that I can use
the set_clip_path() method for and still get what I want?
Thanks,
Alex
--
Alex Goodman
Graduate Research Assistant
Department of Atmospheric Science
Colorado State University
<>--
Learn the latest--Visual Studio 2012, SharePoint 2013, SQL 2012, more!
Discover the easy way to master current and previous Microsoft technologies
and advance your career. Get an incredible 1,500+ hours of step-by-step
tutorial videos with LearnDevNow. Subscribe today and save!
http://pubads.g.doubleclick.net/gampad/clk?id=58040911&iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] Clipping a plot inside a polygon
Hi Phil,
Thanks, that is more or less what I was looking for. However, I still think
that generalizing this approach for other types of plotting functions that
don't return artists directly would be useful. Your solution gave me
another idea for doing this, which would be to iterate through all of the
child artists on the axes using the get_children() method and then calling
set_clip_path() on each artist. This would make the methodology very
general but I am not sure if there are any negative side effects to
resetting the clip path on the other artists besides the PatchCollections.
I modified my simple example script and it seems to work well for
contourf(), pcolor(), and imshow():
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import RegularPolygon
data = np.arange(100).reshape(10, 10)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.contourf(data)
poly = RegularPolygon([ 0.5, 0.5], 6, 0.4, fc='none',
ec='k', transform=ax.transAxes)
for artist in ax.get_children():
artist.set_clip_path(poly)
ax.add_patch(poly)
ax.set_aspect('equal')
ax.axis('off')
plt.show()
Also, I appreciated the cartopy example. I think it has the potential to be
a good basemap replacement thanks to the more robust shapefile support
(which you have very elegantly shown), and I hope the development goes well.
Thanks,
Alex
On Mon, Sep 2, 2013 at 2:33 AM, Phil Elson wrote:
> Great question. The contour set itself does not have a set_clip_path
> method but you can iterate over each of the contour collections and set
> their respective clip paths, i.e.:
>
> cs = plt.contourf(data)
> for collection in cs.collections:
> collection.set_clip_path(poly)
>
> Of course, you can use this approach in either Basemap or cartopy, but
> I've put together an example of doing it in cartopy to demonstrate the neat
> Shapely integration: http://nbviewer.ipython.org/6410510
>
> HTH,
>
> Phil
>
>
> On 2 September 2013 05:40, Alex Goodman wrote:
>
>> Hi all,
>>
>> I want to be able to plot data on maps (using basemap or cartopy) inside
>> specific regions, eg a single state, province or country. A similar
>> question was asked a long time ago on the mailing list and the suggested
>> solution back then was to read the bounding polygon from a shapefile and
>> then check if each individual point was inside that polygon. Currently I
>> have no problem doing this if I use matplotlib.path.Path.contains_points()
>> to mask the original data array, but the disadvantage to this solution is
>> that it is very slow. Another solution that I have discovered recently is
>> to use the set_clip_path() method for artists. In addition to being much
>> faster, this also makes the areas near the polygon boundary look much
>> smoother since the actual items being clipped are individual pixels and not
>> data points.
>>
>> Here is an example script that plots an image via imshow, but the only
>> part of the image that gets shown is inside the hexagon.
>>
>> import numpy as np
>> import matplotlib.pyplot as plt
>> from matplotlib.patches import RegularPolygon
>>
>> data = np.arange(100).reshape(10, 10)
>> fig = plt.figure()
>> ax = fig.add_subplot(111)
>> im = ax.imshow(data)
>> poly = RegularPolygon([ 0.5, 0.5], 6, 0.4, fc='none',
>> ec='k', transform=ax.transAxes)
>> im.set_clip_path(poly)
>> ax.add_patch(poly)
>> ax.axis('off')
>> plt.show()
>>
>> While this does seem like an ideal solution, it doesn't work for every
>> type of plot. The most notable example is contourf(). It returns a
>> QuadContourSet instance which does not inherit from Artist, so it does not
>> contain the set_clip_path() method. My main question is whether there is a
>> mechanism in matplotlib that can convert something like a QuadContourSet
>> into an image so I can make use of this solution for contourf() as well. Or
>> better yet, is there perhaps another artist within the axes that I can use
>> the set_clip_path() method for and still get what I want?
>>
>> Thanks,
>> Alex
>> --
>> Alex Goodman
>> Graduate Research Assistant
>> Department of Atmospheric Science
>> Colorado State University
>>
>>
>> --
>> Learn the latest--Visual Studio 2012, SharePoint 2013, SQL 2012, more!
>> Discover the easy way to master current and previous Microsoft
>> technologies
>> and advance your career. Get an incredible 1,500+ hours of step-by-step
>> tutorial videos with LearnDevNow. Subscribe today and save!
>>
>&
Re: [Matplotlib-users] Clipping a plot inside a polygon
Actually, it seems I have partially answered my own question. Since I am
calling axis('off'), I do not notice the effect of clipping the other
artists since I made a call to axis('off'). Without it the spines and axes
rectangle are still removed but the ticks are still visible. I suppose this
is fine for my own purposes of contouring within one country on a map since
I would want to use something like axis('off') anyway, but then it would
not work if I wanted to use the axes background. Another approach I have
tried is to use the clip_path keyword in the plotting functions themselves,
which works for imshow and pcolor, but not contourf. Any other ideas?
Alex
On Mon, Sep 2, 2013 at 12:18 PM, Alex Goodman wrote:
> Hi Phil,
>
> Thanks, that is more or less what I was looking for. However, I still
> think that generalizing this approach for other types of plotting functions
> that don't return artists directly would be useful. Your solution gave me
> another idea for doing this, which would be to iterate through all of the
> child artists on the axes using the get_children() method and then calling
> set_clip_path() on each artist. This would make the methodology very
> general but I am not sure if there are any negative side effects to
> resetting the clip path on the other artists besides the PatchCollections.
> I modified my simple example script and it seems to work well for
> contourf(), pcolor(), and imshow():
>
> import numpy as np
> import matplotlib.pyplot as plt
> from matplotlib.patches import RegularPolygon
>
> data = np.arange(100).reshape(10, 10)
> fig = plt.figure()
> ax = fig.add_subplot(111)
> ax.contourf(data)
> poly = RegularPolygon([ 0.5, 0.5], 6, 0.4, fc='none',
> ec='k', transform=ax.transAxes)
> for artist in ax.get_children():
> artist.set_clip_path(poly)
>
> ax.add_patch(poly)
> ax.set_aspect('equal')
> ax.axis('off')
> plt.show()
>
>
> Also, I appreciated the cartopy example. I think it has the potential to
> be a good basemap replacement thanks to the more robust shapefile support
> (which you have very elegantly shown), and I hope the development goes well.
>
> Thanks,
> Alex
>
>
> On Mon, Sep 2, 2013 at 2:33 AM, Phil Elson wrote:
>
>> Great question. The contour set itself does not have a set_clip_path
>> method but you can iterate over each of the contour collections and set
>> their respective clip paths, i.e.:
>>
>> cs = plt.contourf(data)
>> for collection in cs.collections:
>> collection.set_clip_path(poly)
>>
>> Of course, you can use this approach in either Basemap or cartopy, but
>> I've put together an example of doing it in cartopy to demonstrate the neat
>> Shapely integration: http://nbviewer.ipython.org/6410510
>>
>> HTH,
>>
>> Phil
>>
>>
>> On 2 September 2013 05:40, Alex Goodman wrote:
>>
>>> Hi all,
>>>
>>> I want to be able to plot data on maps (using basemap or cartopy) inside
>>> specific regions, eg a single state, province or country. A similar
>>> question was asked a long time ago on the mailing list and the suggested
>>> solution back then was to read the bounding polygon from a shapefile and
>>> then check if each individual point was inside that polygon. Currently I
>>> have no problem doing this if I use matplotlib.path.Path.contains_points()
>>> to mask the original data array, but the disadvantage to this solution is
>>> that it is very slow. Another solution that I have discovered recently is
>>> to use the set_clip_path() method for artists. In addition to being much
>>> faster, this also makes the areas near the polygon boundary look much
>>> smoother since the actual items being clipped are individual pixels and not
>>> data points.
>>>
>>> Here is an example script that plots an image via imshow, but the only
>>> part of the image that gets shown is inside the hexagon.
>>>
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from matplotlib.patches import RegularPolygon
>>>
>>> data = np.arange(100).reshape(10, 10)
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> im = ax.imshow(data)
>>> poly = RegularPolygon([ 0.5, 0.5], 6, 0.4, fc='none',
>>> ec='k', transform=ax.transAxes)
>>> im.set_clip_path(poly)
>>> ax.add_patch(poly)
>>> ax.axis('off')
>>> plt.show()
>>>
>>> While this does seem like an ideal solution, it doesn't work for every
>>> t
Re: [Matplotlib-users] Clipping a plot inside a polygon
Actually, sorry for the triple post, but is there a reason why we can't do
something like pass in the keyword arguments directly from the call to
contourf when instantiating each collection? Then the keyword arguments for
contourf (and ContourSet) could be used for the collections directly,
including clip_path. I know a similar approach is taken for the keyword
arguments in plot, since those can be used to modify the properties of each
Line2D instance.
Thanks,
Alex
On Mon, Sep 2, 2013 at 1:09 PM, Alex Goodman wrote:
> Actually, it seems I have partially answered my own question. Since I am
> calling axis('off'), I do not notice the effect of clipping the other
> artists since I made a call to axis('off'). Without it the spines and axes
> rectangle are still removed but the ticks are still visible. I suppose this
> is fine for my own purposes of contouring within one country on a map since
> I would want to use something like axis('off') anyway, but then it would
> not work if I wanted to use the axes background. Another approach I have
> tried is to use the clip_path keyword in the plotting functions themselves,
> which works for imshow and pcolor, but not contourf. Any other ideas?
>
> Alex
>
>
> On Mon, Sep 2, 2013 at 12:18 PM, Alex Goodman
> wrote:
>
>> Hi Phil,
>>
>> Thanks, that is more or less what I was looking for. However, I still
>> think that generalizing this approach for other types of plotting functions
>> that don't return artists directly would be useful. Your solution gave me
>> another idea for doing this, which would be to iterate through all of the
>> child artists on the axes using the get_children() method and then calling
>> set_clip_path() on each artist. This would make the methodology very
>> general but I am not sure if there are any negative side effects to
>> resetting the clip path on the other artists besides the PatchCollections.
>> I modified my simple example script and it seems to work well for
>> contourf(), pcolor(), and imshow():
>>
>> import numpy as np
>> import matplotlib.pyplot as plt
>> from matplotlib.patches import RegularPolygon
>>
>> data = np.arange(100).reshape(10, 10)
>> fig = plt.figure()
>> ax = fig.add_subplot(111)
>> ax.contourf(data)
>> poly = RegularPolygon([ 0.5, 0.5], 6, 0.4, fc='none',
>> ec='k', transform=ax.transAxes)
>> for artist in ax.get_children():
>> artist.set_clip_path(poly)
>>
>> ax.add_patch(poly)
>> ax.set_aspect('equal')
>> ax.axis('off')
>> plt.show()
>>
>>
>> Also, I appreciated the cartopy example. I think it has the potential to
>> be a good basemap replacement thanks to the more robust shapefile support
>> (which you have very elegantly shown), and I hope the development goes well.
>>
>> Thanks,
>> Alex
>>
>>
>> On Mon, Sep 2, 2013 at 2:33 AM, Phil Elson wrote:
>>
>>> Great question. The contour set itself does not have a set_clip_path
>>> method but you can iterate over each of the contour collections and set
>>> their respective clip paths, i.e.:
>>>
>>> cs = plt.contourf(data)
>>> for collection in cs.collections:
>>> collection.set_clip_path(poly)
>>>
>>> Of course, you can use this approach in either Basemap or cartopy, but
>>> I've put together an example of doing it in cartopy to demonstrate the neat
>>> Shapely integration: http://nbviewer.ipython.org/6410510
>>>
>>> HTH,
>>>
>>> Phil
>>>
>>>
>>> On 2 September 2013 05:40, Alex Goodman wrote:
>>>
>>>> Hi all,
>>>>
>>>> I want to be able to plot data on maps (using basemap or cartopy)
>>>> inside specific regions, eg a single state, province or country. A similar
>>>> question was asked a long time ago on the mailing list and the suggested
>>>> solution back then was to read the bounding polygon from a shapefile and
>>>> then check if each individual point was inside that polygon. Currently I
>>>> have no problem doing this if I use matplotlib.path.Path.contains_points()
>>>> to mask the original data array, but the disadvantage to this solution is
>>>> that it is very slow. Another solution that I have discovered recently is
>>>> to use the set_clip_path() method for artists. In addition to being much
>>>> faster, this also makes the areas near the polygon boundary look much
>>>> smoother since the actual items being clipped are individual pixels and no
Re: [Matplotlib-users] could I get rid of the contour of Antarctica by using Basemap?
A quick apology for a typo in my previous message, the method in question is drawcoastlines(), not drawcontinents(). The code snippet should still be correct though! On Mon, Dec 30, 2013 at 7:09 PM, Alex Goodman wrote: > Hi Chao, > > Actually it is possible to remove the borders for Antarctica with basemap. > The default method for drawing the continents in basemap, drawcontinents(), > returns an instance of matplotlib.collections.LineCollection. What you will > want to do is manually remove the line segments within the collection that > correspond to Antarctica. For example, > > # m is a Basemap instance > lcol = m.drawcoastlines() > segs = lcol.get_segments() > > for i, seg in enumerate(segs): > # The segments are lists of ordered pairs in spherical (lon, lat), > coordinates. > # We can filter out which ones correspond to Antarctica based on > latitude using numpy.any() > if np.any(seg[:, 1] < -60): > segs.pop(i) > > lcol.set_segments(segs) > > This should do the trick unless I made a silly typo somewhere. > > Thanks, > Alex > > > On Mon, Dec 30, 2013 at 5:05 PM, Sterling Smith wrote: > >> Chao, >> >> I know nothing of the Basemap toolkit so I can't comment on the removal >> of continents, but presumably the text command you are using takes some >> keywords to set the properties of the bounding box. Try setting the >> background of the bounding box to white so that your words show up cleanly. >> Feel free to let me know that I'm barking up the wrong tree. >> >> -Sterling >> >> On Dec 30, 2013, at 3:46PM, Chao YUE wrote: >> >> > Dear all, >> > >> > Happy new year! >> > >> > I am using Basemap toolkit to make some maps, I would like to >> > write something at the bottom of the map, whose position is now >> > taken by the contourf of Antarctica. Is there a way I can keep contours >> > of other continents but suppressing the one for antarctica? I attached >> > showing why I would like to have this. >> > >> > thanks for any help, >> > >> > Chao >> > -- >> > >> *** >> > Chao YUE >> > Laboratoire des Sciences du Climat et de l'Environnement (LSCE-IPSL) >> > UMR 1572 CEA-CNRS-UVSQ >> > Batiment 712 - Pe 119 >> > 91191 GIF Sur YVETTE Cedex >> > Tel: (33) 01 69 08 29 02; Fax:01.69.08.77.16 >> > >> >> > >> -- >> > Rapidly troubleshoot problems before they affect your business. Most IT >> > organizations don't have a clear picture of how application performance >> > affects their revenue. With AppDynamics, you get 100% visibility into >> your >> > Java,.NET, & PHP application. Start your 15-day FREE TRIAL of >> AppDynamics Pro! >> > >> http://pubads.g.doubleclick.net/gampad/clk?id=84349831&iu=/4140/ostg.clktrk___ >> > Matplotlib-users mailing list >> > [email protected] >> > https://lists.sourceforge.net/lists/listinfo/matplotlib-users >> >> >> >> -- >> Rapidly troubleshoot problems before they affect your business. Most IT >> organizations don't have a clear picture of how application performance >> affects their revenue. With AppDynamics, you get 100% visibility into your >> Java,.NET, & PHP application. Start your 15-day FREE TRIAL of AppDynamics >> Pro! >> >> http://pubads.g.doubleclick.net/gampad/clk?id=84349831&iu=/4140/ostg.clktrk >> ___ >> Matplotlib-users mailing list >> [email protected] >> https://lists.sourceforge.net/lists/listinfo/matplotlib-users >> > > > > -- > Alex Goodman > Graduate Research Assistant > Department of Atmospheric Science > Colorado State University > -- Alex Goodman Graduate Research Assistant Department of Atmospheric Science Colorado State University -- Rapidly troubleshoot problems before they affect your business. Most IT organizations don't have a clear picture of how application performance affects their revenue. With AppDynamics, you get 100% visibility into your Java,.NET, & PHP application. Start your 15-day FREE TRIAL of AppDynamics Pro! http://pubads.g.doubleclick.net/gampad/clk?id=84349831&iu=/4140/ostg.clktrk___ Matplotlib-users mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] [os x] Can't get IPython to use latest version of matplotlib
Hi Tim, Whenever you have two python versions installed to one machine, it is generally a good practice to set your PATH environment variable to the directory where the python executable you want to use currently lies, and make it permanent by adding it to your ~/.bash_profile file (on MacOSX). Say your python.org version of python was installed in /something/bin. Then add the following line to your ~/.bash_profile: export PATH=/something/bin:$PATH Then run these commands: source ~/.bash_profile which python which pip If the output is /something/bin, then you are good to go; pip should then install matplotlib in the correct place. Hope that helps. Thanks, Alex On Fri, Feb 21, 2014 at 4:58 PM, Timothy Duly wrote: > Paul, > > Do you know how to to get pip install on python.org's version? > > Thanks, > Tim > > > On Fri, Feb 21, 2014 at 5:53 PM, Paul Hobson wrote: > >> It appears that you have two different version of python installed >> (Apple's 2.7.3 and python.org's 2.7.5). You have to install all >> third-party packages to the correct one. It appears pip in acting on >> Apple's python. >> >> >> On Fri, Feb 21, 2014 at 2:08 PM, Timothy Duly wrote: >> >>> Hello, >>> >>> I recently upgraded matplotlib, which was relatively simple: >>> >>> sudo pip install matplotlib --upgrade >>> >>> I checked to make sure I did indeed upgrade: >>> >>> [~]$ python >>> Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) >>> [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import matplotlib; matplotlib.__version__ >>> '1.3.1' >>> >>> Success. However, when I do the same in IPython, I get the old version: >>> >>> [~]$ ipython --pylab >>> Python 2.7.5 (default, Aug 25 2013, 00:04:04) >>> Type "copyright", "credits" or "license" for more information. >>> IPython 1.2.0 -- An enhanced Interactive Python. >>> ? -> Introduction and overview of IPython's features. >>> %quickref -> Quick reference. >>> help -> Python's own help system. >>> object? -> Details about 'object', use 'object??' for extra details. >>> Using matplotlib backend: MacOSX >>> In [1]: import matplotlib; matplotlib.__version__ >>> Out[1]: '1.1.1' >>> >>> Anyone know why this is the case? How do I point IPython to the newest >>> version of matplotlib? >>> >>> I tried googling, but wasn't sure how to zero in on the answer with a >>> search. Also, I'm not sure if this question is best suited for IPython >>> people. >>> >>> Thanks, >>> Tim >>> >>> >>> -- >>> Managing the Performance of Cloud-Based Applications >>> Take advantage of what the Cloud has to offer - Avoid Common Pitfalls. >>> Read the Whitepaper. >>> >>> http://pubads.g.doubleclick.net/gampad/clk?id=121054471&iu=/4140/ostg.clktrk >>> ___ >>> Matplotlib-users mailing list >>> [email protected] >>> https://lists.sourceforge.net/lists/listinfo/matplotlib-users >>> >>> >> > > > -- > - > Timothy M. Duly > Graduate Research Assistant > Remote Sensing & Space Sciences Group > Department of Electrical and Computer Engineering > University of Illinois at Urbana-Champaign > airglow.csl.illinois.edu > - > > > -- > Managing the Performance of Cloud-Based Applications > Take advantage of what the Cloud has to offer - Avoid Common Pitfalls. > Read the Whitepaper. > > http://pubads.g.doubleclick.net/gampad/clk?id=121054471&iu=/4140/ostg.clktrk > ___ > Matplotlib-users mailing list > [email protected] > https://lists.sourceforge.net/lists/listinfo/matplotlib-users > > -- Alex Goodman Graduate Research Assistant Department of Atmospheric Science Colorado State University -- Managing the Performance of Cloud-Based Applications Take advantage of what the Cloud has to offer - Avoid Common Pitfalls. Read the Whitepaper. http://pubads.g.doubleclick.net/gampad/clk?id=121054471&iu=/4140/ostg.clktrk___ Matplotlib-users mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] Area averaged
Hi Fadzil,
All you actually need to do is use numpy.average(), which is numpy's
implementation of the weighted average. It can be shown geometrically that
using the cosine of the latitude as the weights in the weighted average
would give you approximately the area average, though if your SST data has
a grid cell area attribute in the netcdf file, that would be the most
suitable choice to use as your weights. Otherwise, you could determine the
area weighted average as follows:
# numpy is imported as np, lat are the latitudes extracted from the netcdf
file
# First we need to convert the latitudes to radians
latr = np.deg2rad(lat)
# Use the cosine of the converted latitudes as weights for the average
weights = np.cos(latr)
# Assuming the shape of your data array is (nTimes, nLats, nLons)
# First find the zonal mean SST by averaging along the latitude circles
sst = sstv[:]
sst_ave_zonal = sst.mean(axis=2)
# Then take the weighted average of those using the weights we calculated
earlier
sst_ave = np.average(sst_ave_zonal, axis=1, weights=weights)
This should give a time series of global mean SST. Is this what you wanted?
Thanks,
Alex
On Sun, Feb 23, 2014 at 10:28 AM, Fadzil Mnor wrote:
> Hi,
> I just started using Python for the last few weeks, and previously been
> using GrADS for around 4 years.
> I have trouble looking for a simplest way to calculate area average, let
> say I need to calculate a SST over a region of 20S-10N and 130E-170E.
> I know how to get one point values of SST vs Time, as in:
>
>
> ...
> ...
> f = nc.Dataset('d:/data/sst.mon.mean.nc', 'r')
> sstv = f.variables['sst']
> timev = f.variables['time']
> sst = sstv[:, 35, 100]
> plt.plot(timev,sst)
> plt.show()
> ...
> ...
> ***
> but I couldn't figure out how to get an area average value (...and didn't
> get the right reference in the internet either)
> Something missing, probably because I don't understand enough about
> slicing or something else.
> Can anyone give me a hint ?
>
> Thanks.
>
> Fadzil.
>
>
>
>
>
> --
> Managing the Performance of Cloud-Based Applications
> Take advantage of what the Cloud has to offer - Avoid Common Pitfalls.
> Read the Whitepaper.
>
> http://pubads.g.doubleclick.net/gampad/clk?id=121054471&iu=/4140/ostg.clktrk
> _______
> Matplotlib-users mailing list
> [email protected]
> https://lists.sourceforge.net/lists/listinfo/matplotlib-users
>
>
--
Alex Goodman
Graduate Research Assistant
Department of Atmospheric Science
Colorado State University
--
Managing the Performance of Cloud-Based Applications
Take advantage of what the Cloud has to offer - Avoid Common Pitfalls.
Read the Whitepaper.
http://pubads.g.doubleclick.net/gampad/clk?id=121054471&iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] Area averaged
Hi Fadzil, Ah sorry, I glossed over that part of your question. There are actually two solutions to this, one would be to actually find the indices where the latitudes and longitudes are within your desired bounds using numpy.where(). However I generally prefer to use numpy's built-in fancy indexing for this type of problem. For example: # lat and lon are extracted from the netcdf file, assumed to be 1D # Determine which latitudes are between 20S and 10N latidx = (lat >= -20) & (lat <= 10) # Determine which longitudes are between 130E and 170E. # The numbers here may differ depending on the longitude convention in your data. lonidx = (lon >= 130) & (lon <= 170) # Now we will actually subset the data. We need to subset lat too to make sure weights are consistent. sst = sstv[:] sst = sst[:, latidx][..., lonidx] lat = lat[latidx] Yes, the indexing does get a little tricky but it should work if you do it this way, then follow the same procedure outlined in the previous email. Thanks, Alex On Sun, Feb 23, 2014 at 6:02 PM, Fadzil Mnor wrote: > Thanks Alex for the reply. > So, that script calculates the global SST. What if when we want to > calculate for only in specific box? For example, SST over this area only: > > --- 10 N > | | > | | > | | > | SST | > | | > | | > --- 20 S > 130 E 170E > > Thanks. > > Fadzil > -- Alex Goodman Graduate Research Assistant Department of Atmospheric Science Colorado State University -- Flow-based real-time traffic analytics software. Cisco certified tool. Monitor traffic, SLAs, QoS, Medianet, WAAS etc. with NetFlow Analyzer Customize your own dashboards, set traffic alerts and generate reports. Network behavioral analysis & security monitoring. All-in-one tool. http://pubads.g.doubleclick.net/gampad/clk?id=126839071&iu=/4140/ostg.clktrk___ Matplotlib-users mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] Can't plot NCEP reanalysis data
Hi Fadzil,
I am not sure if I fully understand your question. Are you simply trying to
write a general script that plots contours for atmospheric netcdf data? At
the very least, your error message has a very simple explanation in that
the third argument of contourf (in this case, pcpr or omg?) must be a 2D
array with shape (Xsize, Ysize). For data with one vertical level, it would
be reasonable to expect the script to work, but if you have multiple
vertical levels and don't select a specific one in your code, then you
can't use contourf, simple as that.
Does that help at all?
Alex
On Tue, Mar 4, 2014 at 8:22 PM, Fadzil Mnor wrote:
> Hi all,
> I've been looking for solution on this for days, and seems like nothing
> works.
> I wrote this code to read TRMM data and it works, but somehow not working
> when I use the same script to read NCEP reanalysis data...which later I
> found out it worked for netCDF files with only 1 'level' (Zsize=1), not
> multiple 'levels' (Zsize more than 1).
> I'm stuck at where went wrong, and I tried everything and lost of track
> what the error massages were.
> This is what I wrote to read and plot NCEP reanalysis data. (this omega
> data has Xsize=144, Ysize=73, Zsize=12, Tsize=792, Esize=1)
>
> ---
> *import netCDF4 as nc*
> *import matplotlib.pyplot as plt*
> *from mpl_toolkits.basemap import Basemap*
> *import numpy as np*
>
> *f = nc.Dataset('D:/data/omega.mon.mean.nc
> <http://omega.mon.mean.nc>','r')*
> *omg = f.variables['omega'][0]*
> *lon = f.variables['lon'][:]*
> *lat = f.variables['lat'][:]*
> *times = f.variables['time'][:]*
>
> *# Set up a map *
> *map =
> Basemap(projection='cyl',llcrnrlat=0.,urcrnrlat=10.,llcrnrlon=97.,urcrnrlon=110.,resolution='i')*
> *x,y=map(*np.meshgrid(lon,lat))*
> *map.drawcoastlines()*
> *map.drawcountries()*
> *map.drawparallels(np.arange(-90.,90.,3),labels=[1,0,0,0],fontsize=10)*
> *map.drawmeridians(np.arange(-180.,180.,3),labels=[0,0,0,1],fontsize=10)*
>
> *#contour data*
> *clevs=np.arange(0.,1.,0.1) # contour interval*
> *cs = map.contourf(x,y,pcpr,clevs,extent='both')*
> *cb = map.colorbar(cs,'bottom',size='2%',pad="5%") #plot the colorbar *
>
> *cb.set_label('m/s')*
> *plt.title('Omega-test')*
>
> *plt.show()*
>
> *f.close()*
>
> -
>
> Above code gave error: Input z must be a 2D array
> (that's at *cs = map.contourf(x,y,pcpr,clevs,extent='both')*...)
>
> Hopefully anyone can help.
> Thanks for your time reading this.
>
> Fadzil
>
>
>
>
> --
> Subversion Kills Productivity. Get off Subversion & Make the Move to
> Perforce.
> With Perforce, you get hassle-free workflows. Merge that actually works.
> Faster operations. Version large binaries. Built-in WAN optimization and
> the
> freedom to use Git, Perforce or both. Make the move to Perforce.
>
> http://pubads.g.doubleclick.net/gampad/clk?id=122218951&iu=/4140/ostg.clktrk
> ___
> Matplotlib-users mailing list
> [email protected]
> https://lists.sourceforge.net/lists/listinfo/matplotlib-users
>
>
--
Alex Goodman
Graduate Research Assistant
Department of Atmospheric Science
Colorado State University
--
Subversion Kills Productivity. Get off Subversion & Make the Move to Perforce.
With Perforce, you get hassle-free workflows. Merge that actually works.
Faster operations. Version large binaries. Built-in WAN optimization and the
freedom to use Git, Perforce or both. Make the move to Perforce.
http://pubads.g.doubleclick.net/gampad/clk?id=122218951&iu=/4140/ostg.clktrk___
Matplotlib-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] CAPE and CIN calculation in Python
You can easily visualize the CAPE and CIN with matplotlib using fill_between() on the environmental and parcel temperature curves. As for actually calculating it though, I don't know of a way to do it directly from matplotlib. There are probably several other python packages out there that can, but I am not familiar with them. In any case, why not just write your own function for calculating the CAPE and CIN? It is a bit surprising that this functionality isn't be included in the SkewT package, but since you can use it to get the parcel temperature curve, you should be able to calculate the CAPE and CIN rather easily by simply discretizing their respective formulas. Here's a rough example: import numpy as np cape = 9.8 * np.sum(dz * (Tp - T) / T) Where Tp and T are the parcel and environmental temperature arrays respectively, and dz are the height differences between layers. You would of course need to perform the sum from the LFC to EL for CAPE, so the arrays would have to to be subsetted. With numpy the easiest way to do this is with fancy indexing, eg: levs = (z >= LFC) & (z <= EL) Tp = Tp[levs] T = T[levs] where z is your array of heights (or pressure levels). Does this help? Alex On Sat, Mar 29, 2014 at 4:32 PM, Gökhan Sever wrote: > Hello, > > Lately, I am working on plotting sounding profiles on a SkewT/LogP > diagram. The SkewT package which is located at > https://github.com/tchubb/SkewT has a nice feature to lift a parcel on > dry/moist adiabats. This is very useful to demonstrate the regions of CIN > and CAPE overlaid with the full sounding. > > However, the package misses these diagnostic calculations. This is the > only step holding me back to use Python only (migrating from NCL) for my > plotting tasks. I am aware that these calculations are usually performed > in fortran. Are there any routines wrapped in Python to calculate CAPE and > CIN parameters? Any suggestions or comments would be really appreciated. > > -- > Gökhan > > > -- > > ___ > Matplotlib-users mailing list > [email protected] > https://lists.sourceforge.net/lists/listinfo/matplotlib-users > > -- Alex Goodman Graduate Research Assistant Department of Atmospheric Science Colorado State University -- ___ Matplotlib-users mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] One colorbar for many plot
I would consider using the AxesGrid toolkit [1], which makes it very easy to have a single colorbar for multiple plots. [1] - http://matplotlib.org/1.3.1/mpl_toolkits/axes_grid/users/overview.html Thanks, Alex On Tue, May 20, 2014 at 8:04 PM, Alex Goodman wrote: > I would consider using the AxesGrid toolkit [1], which makes it very easy > to have a single colorbar for multiple plots. > > [1] - > http://matplotlib.org/1.3.1/mpl_toolkits/axes_grid/users/overview.html > > Thanks, > Alex > > > On Tue, May 20, 2014 at 7:57 PM, Dyah rahayu martiningrum < > [email protected]> wrote: > >> I am a newbie in python and I try to plot data like below : >> >> base_dir = 'C:/DATA2013/Day_E/' >> nc_fnames = ['20130203.faieb3p4g.nc', >> '20130203.faieb3p4g.nc','20130203.faieb3p4g.nc'] >> # beams >> ibeams = [0,1,2] >> # Change directory >> os.chdir(base_dir) >> for i, fname in enumerate(nc_fnames): >> >># Open file >> fd = nc.Dataset(fname, 'r') >> >> # Read variables >> beam = fd.variables['beam'][:] >> rng = fd.variables['range'][:] >> tim = fd.variables['time'][:] >> pwr = fd.variables['pwr'][:] >> nfft = fd.variables['nfft'][0] >> pn = fd.variables['pnoise'][:] >> >> # Close netCDF file >> fd.close() >> >> # Specify beam >> ibeam = ibeams[i] >> >> # Time convertion >> tim = tim/3600.0 >> >> #Plot >> p_plot = pwr[ibeam] >> >> for it in range(len(tim)): >> p_plot[it] = p_plot[it] - pn[ibeam][it] - 10.*np.log10(nfft) >> >> p_plot = p_plot.transpose() >> #Specify subplot >> pl.subplot(311 + i)#Contour plot >> pl.contourf(tim, rng, p_plot)#Plot colorbar >> pl.colorbar() >> # Set X and Y axis lower/upper limit >> set_xy = range(4) >> set_xy[0] = 18.0 # x min >> set_xy[1] = 30.0 # x max >> set_xy[2] = 90.0 # y min >> set_xy[3] = 170.0 # y max >> pl.axis(set_xy) >> # Set labels >> pl.xlabel('time (hours)') >> pl.ylabel('range (km)') >> >> pl.show() >> >> >> The result looks like three panels with different colorbar for each >> panel. How do I make only one colorbar for all panels? Thank you in advance. >> >> >> ------ >> "Accelerate Dev Cycles with Automated Cross-Browser Testing - For FREE >> Instantly run your Selenium tests across 300+ browser/OS combos. >> Get unparalleled scalability from the best Selenium testing platform >> available >> Simple to use. Nothing to install. Get started now for free." >> http://p.sf.net/sfu/SauceLabs >> ___ >> Matplotlib-users mailing list >> [email protected] >> https://lists.sourceforge.net/lists/listinfo/matplotlib-users >> >> > > > -- > Alex Goodman > Graduate Research Assistant > Department of Atmospheric Science > Colorado State University > -- Alex Goodman Graduate Research Assistant Department of Atmospheric Science Colorado State University -- "Accelerate Dev Cycles with Automated Cross-Browser Testing - For FREE Instantly run your Selenium tests across 300+ browser/OS combos. Get unparalleled scalability from the best Selenium testing platform available Simple to use. Nothing to install. Get started now for free." http://p.sf.net/sfu/SauceLabs___ Matplotlib-users mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] subplots [xy]labels
Hi Giacomo,
Try using the set_ylabel() and set_xlabel() methods for each Axes instance
instead, eg:
a[0].set_ylabel('f1')
a[0].set_xlabel('t')
a[1].set_ylabel('f2')
a[1].set_xlabel('t')
On Fri, Jan 4, 2013 at 5:44 AM, wrote:
> two plots in a figure:
>
> from pylab import *
> ...
> f,a = subplots(nrows=2, sharex=False, sharey=False)
> a[0].plot(x,f0(x))
> ylabel('f1')
> xlabel('t')
> ...
> a[1].plot(x,f1(x))
> ylabel('f2')
> xlabel('t')
> ...
> show()
>
> but all i can get are labels for ONLY the lower subplot, what shoud I do?
>
> any help will be appreciated
>
> tia
> gb
>
>
>
> --
> Master HTML5, CSS3, ASP.NET, MVC, AJAX, Knockout.js, Web API and
> much more. Get web development skills now with LearnDevNow -
> 350+ hours of step-by-step video tutorials by Microsoft MVPs and experts.
> SALE $99.99 this month only -- learn more at:
> http://p.sf.net/sfu/learnmore_122812
> _______
> Matplotlib-users mailing list
> [email protected]
> https://lists.sourceforge.net/lists/listinfo/matplotlib-users
>
--
Alex Goodman
University of Illinois at Urbana-Champaign
Email: [email protected]
--
Master HTML5, CSS3, ASP.NET, MVC, AJAX, Knockout.js, Web API and
much more. Get web development skills now with LearnDevNow -
350+ hours of step-by-step video tutorials by Microsoft MVPs and experts.
SALE $99.99 this month only -- learn more at:
http://p.sf.net/sfu/learnmore_122812___
Matplotlib-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-users
