Re: [Matplotlib-users] The Blue Marble is upside down!
Mauro Cavalcanti wrote: > Dear Jeff & ALL, > > Attached is the latest version of my Basemap embedded in wxPython > sample application. I have added a check menu option that allows one > to toggle the overlay of the Blue Marble image on and off the Basemap > figure. Everything works well -- except that the Blue Marble image is > plotted upside down! I could not figure out the cause of this, say, > rather bizarre behaviour. Any hints? > > Thanks in advance for any assistance you can provide. > > Best regards, > > PS This version has another known bug, to be eventually fixed -- if > the user has plotted a point coordinate file, the points are erased if > the Blue Marble overlay is requested because the PlotMap() routine > calls ax.cla() at the start. > > Mauro: The image flipping looks to be a Wx backend bug - it doesn't happen if you use WxAgg instead. -Jeff P.S. It's not recommended to use tabs in python code. Especially don't mix tabs and spaces (http://www.python.org/dev/peps/pep-0008/). -- Jeffrey S. Whitaker Phone : (303)497-6313 NOAA/OAR/CDC R/PSD1FAX : (303)497-6449 325 BroadwayBoulder, CO, USA 80305-3328 -- SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada. The future of the web can't happen without you. Join us at MIX09 to help pave the way to the Next Web now. Learn more and register at http://ad.doubleclick.net/clk;208669438;13503038;i?http://2009.visitmix.com/ ___ Matplotlib-users mailing list Matplotlib-users@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/matplotlib-users
[Matplotlib-users] anomalous speeds on macosx backend
It's very nice to have a native macosx backend. Many thanks to Michiel. It does seem to work with ipython fine. However, at present, it's not always faster than WXAgg. With matplotlib svn r6575, python 2.5.2, everything compiled with gcc4.0, 10.5.5, macbook pro 2.33GHz, 2GB memory (i) interactive zooming of the plot window seems very slow (ii) in scripts, pcolormesh and pcolor seem much slower than WXAgg, though ax.pcolorfast is faster.. on a 1000x200 array: pcolormesh: [242-132:~/Python] agn% time python testspeed.py -dmacosx 32.717u 1.479s 0:43.76 78.1%0+0k 0+23io 0pf+0w 242-132:~/Python] agn% time python testspeed.py -dWXAgg 1.226u 0.444s 0:05.80 28.6% 0+0k 0+25io 0pf+0w pcolor: [242-132:~/Python] agn% time python testspeed3.py -dmacosx 53.652u 2.099s 2:09.58 43.0%0+0k 0+154io 0pf+0w [242-132:~/Python] agn% time python testspeed3.py -dWXAgg 26.775u 1.542s 0:32.25 87.7%0+0k 0+35io 0pf+0w ax.pcolorfast: [242-132:~/Python] agn% time python testspeed2.py -dmacosx 0.580u 0.331s 0:04.07 22.3% 0+0k 0+2io 0pf+0w [242-132:~/Python] agn% time python testspeed2.py -dWXAgg 0.988u 0.423s 0:04.70 29.7% 0+0k 0+11io 0pf+0w (iii) explicit creation of figure and axes instances seems to slow it down radically in ipython: e.g In [3]: a= numpy.random.rand(100,200) .. a few creations of plots and theitr removal, to get started.. With WxAgg backend: In [8]: time pcolormesh(a) CPU times: user 0.22 s, sys: 0.03 s, total: 0.25 s Wall time: 0.25 s Out[9]: With macosx backend: In [39]: time pcolormesh(a) CPU times: user 0.05 s, sys: 0.01 s, total: 0.06 s Wall time: 0.08 s so, 3x as fast. However, explicitly creating the figure is much slower on macosx: In [26]: time fig=figure();ax=fig.add_subplot(1,1,1);ax.pcolormesh(a);draw() CPU times: user 3.33 s, sys: 0.03 s, total: 3.36 s Wall time: 3.41 s In [37]: time fig=figure();ax=fig.add_subplot(1,1,1);pcolormesh(a);draw() CPU times: user 3.39 s, sys: 0.03 s, total: 3.42 s Wall time: 3.46 s while with wxagg there is little change in speed: In [16]: time fig=figure();ax=fig.add_subplot(1,1,1);ax.pcolormesh(a);draw() CPU times: user 0.21 s, sys: 0.03 s, total: 0.25 s Wall time: 0.25 s --George Nurser. import numpy as np import matplotlib.pyplot as plt a= np.random.rand(1000,200) plt.pcolormesh(a) # plt.savefig('test') plt.show() import numpy as np import matplotlib.pyplot as plt a= np.random.rand(1000,200) fig=plt.figure() ax=fig.add_subplot(1,1,1) ax.pcolorfast(a) # plt.savefig('test') plt.show() import numpy as np import matplotlib.pyplot as plt a= np.random.rand(1000,200) fig=plt.figure() ax=fig.add_subplot(1,1,1) ax.pcolor(a) # plt.savefig('test') plt.show() -- SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada. The future of the web can't happen without you. Join us at MIX09 to help pave the way to the Next Web now. Learn more and register at http://ad.doubleclick.net/clk;208669438;13503038;i?http://2009.visitmix.com/___ Matplotlib-users mailing list Matplotlib-users@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] The Blue Marble is upside down!
On 12/12/2008 7:48 AM Jeff Whitaker apparently wrote: > It's not recommended to use tabs in python code. That is project dependent. And a religious war. (Note that tabs have many advantages. E.g., explicit is better than implicit, and one tab is explicitly one level on indent.) > Especially don't mix tabs and spaces > (http://www.python.org/dev/peps/pep-0008/). True enough. (For indenting.) Maybe PEP 666 should have been accepted. http://www.python.org/dev/peps/pep-0666/ Alan Isaac -- SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada. The future of the web can't happen without you. Join us at MIX09 to help pave the way to the Next Web now. Learn more and register at http://ad.doubleclick.net/clk;208669438;13503038;i?http://2009.visitmix.com/ ___ Matplotlib-users mailing list Matplotlib-users@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/matplotlib-users
[Matplotlib-users] ANN: matplotlib-0.98.5
We have just released a new version of matplotlib, available for download at https://sourceforge.net/project/showfiles.php?group_id=80706&package_id=278194&release_id=646644 It is a simple bugfix release to fix a number of critical bugs found in 0.98.4. These "what's new" release notes, with graphs and links, are available in html at http://matplotlib.sourceforge.net/users/whats_new.html Thanks to Charlie Moad for testing and preparing the source release, including binaries for OS X and Windows for python 2.4 and 2.5 (2.6 and 3.0 will not be available until numpy is available on those releases). Thanks to the many developers who contributed to this release, with contributions from Jae-Joon Lee, Michael Droettboom, Ryan May, Eric Firing, Manuel Metz, Jouni K. Seppaenen, Jeff Whitaker, Darren Dale, David Kaplan, Michiel de Hoon and many others who submitted patches What's new in 0.98.5 == It's only been a matter of days since 0.98.4, but there were a number of critical bugs that warranted a new release. 2008-12-11 Use subprocess.Popen instead of os.popen in dviread (Windows problem reported by Jorgen Stenarson) - JKS 2008-12-10 Added Michael's font_manager fix and Jae-Joon's figure/subplot fix. Bumped version number to 0.98.5 - JDH -- Michael Droettboom Science Software Branch Operations and Engineering Division Space Telescope Science Institute Operated by AURA for NASA -- SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada. The future of the web can't happen without you. Join us at MIX09 to help pave the way to the Next Web now. Learn more and register at http://ad.doubleclick.net/clk;208669438;13503038;i?http://2009.visitmix.com/ ___ Matplotlib-users mailing list Matplotlib-users@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] The Blue Marble is upside down!
Dear Jeff, 2008/12/12 Jeff Whitaker : > Mauro: The image flipping looks to be a Wx backend bug - it doesn't happen > if you use WxAgg instead. Thank you very much. It works quite well with WxAgg. Incidentally, the WXAgg backend also provides for a slightly better and faster rendering (not of the Blue Marble itself, but of usual maps). > P.S. It's not recommended to use tabs in python code. Especially don't mix > tabs and spaces (http://www.python.org/dev/peps/pep-0008/). I do agree that tabs and spaces have *never* to be mixed. The mixing of tabs and spaces may be a misconfiguration of the IDE I use (DrPython). Have to check. With best regards, -- Dr. Mauro J. Cavalcanti Ecoinformatics Studio P.O. Box 46521, CEP 20551-970 Rio de Janeiro, RJ, BRASIL E-mail: mauro...@gmail.com Web: http://studio.infobio.net Linux Registered User #473524 * Ubuntu User #22717 "Life is complex. It consists of real and imaginary parts." -- SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada. The future of the web can't happen without you. Join us at MIX09 to help pave the way to the Next Web now. Learn more and register at http://ad.doubleclick.net/clk;208669438;13503038;i?http://2009.visitmix.com/ ___ Matplotlib-users mailing list Matplotlib-users@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] Font problem
Jouni K. Seppänen skrev: > Michael Droettboom writes: > >> Jörgen Stenarson wrote: >>> I tried to use usetex to generate my pdf figures but I got a crash >>> when saving the figure, log attached. I traced the crash to >>> find_tex_file(), apparently ' can not be used to quote filenames in >>> the windows shell it has to be ". In my patch I just changed it to >>> always use " I don't know if that works on other systems. >> Someone who knows about usetex should review and apply this patch. > > In Unix shells ' is the better quoting character because all sorts of > things have special meaning within " characters... but I changed it to > use subprocess.Popen instead, so we shouldn't need to worry about shell > quoting at all. > > Jörgen: Thanks for your report, which I think is the first one from a > Windows user using usetex with the pdf backend. Can you check that the > latest version on the trunk works (either by updating from svn or by > applying the attached patch)? Have you run into any other problems? What > TeX distribution are you using? > It works from current svn. I'm running miktex2.7. I have seen some font mismatch problems but I'm not sure they are bugs. But I will get back to you on those. /Jörgen -- SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada. The future of the web can't happen without you. Join us at MIX09 to help pave the way to the Next Web now. Learn more and register at http://ad.doubleclick.net/clk;208669438;13503038;i?http://2009.visitmix.com/ ___ Matplotlib-users mailing list Matplotlib-users@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/matplotlib-users
[Matplotlib-users] Matplotlib 0.98.5 egg on Mac OS X : Install Problem
Hi Everyone, I am running into a problem when trying to install 0.98.5 egg on a Mac OS X machine. Any help much appreciated. Relevant error messages follow: Thanks -Kaushik sudo easy_install matplotlib-0.98.5-py2.5-macosx-10.3.egg** BUILDING MATPLOTLIB matplotlib: 0.98.5 python: 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] platform: darwin REQUIRED DEPENDENCIES numpy: 1.2.1 freetype2: found, but unknown version (no pkg-config) OPTIONAL BACKEND DEPENDENCIES libpng: found, but unknown version (no pkg-config) Tkinter: Tkinter: 50704, Tk: 8.4, Tcl: 8.4 wxPython: no * wxPython not found Gtk+: no * Building for Gtk+ requires pygtk; you must be able * to "import gtk" in your build/install environment Mac OS X native: yes Qt: no Qt4: no Cairo: no OPTIONAL DATE/TIMEZONE DEPENDENCIES datetime: present, version unknown dateutil: matplotlib will provide pytz: 2008c OPTIONAL USETEX DEPENDENCIES dvipng: no ghostscript: /bin/sh: gs: command not found latex: no EXPERIMENTAL CONFIG PACKAGE DEPENDENCIES configobj: matplotlib will provide enthought.traits: no [Edit setup.cfg to suppress the above messages] error: lib/matplotlib/mpl-data/matplotlib.conf.template: No such file or directory Exception exceptions.OSError: (2, 'No such file or directory', 'src/image.cpp') in > ignored Exception exceptions.OSError: (2, 'No such file or directory', 'src/path.cpp') in > ignored Exception exceptions.OSError: (2, 'No such file or directory', 'src/backend_agg.cpp') in > ignored From within ipython:*** In [1]: import pylab --- ImportError Traceback (most recent call last) /Users/kghose/ in () /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib-0.98.5-py2.5-macosx-10.3.egg/pylab.py in () > 1 from matplotlib.pylab import * 2 import matplotlib.pylab 3 __doc__ = matplotlib.pylab.__doc__ /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib-0.98.5-py2.5-macosx-10.3.egg/matplotlib/pylab.py in () 204 from numpy import ma 205 --> 206 from matplotlib import mpl # pulls in most modules 207 208 from matplotlib.dates import date2num, num2date,\ /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib-0.98.5-py2.5-macosx-10.3.egg/matplotlib/mpl.py in () 2 from matplotlib import axis > 3 from matplotlib import axes 4 from matplotlib import cbook 5 from matplotlib import collections 6 from matplotlib import colors /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib-0.98.5-py2.5-macosx-10.3.egg/matplotlib/axes.py in () 16 import matplotlib.dates as mdates 17 import matplotlib.font_manager as font_manager ---> 18 import matplotlib.image as mimage 19 import matplotlib.legend as mlegend 20 import matplotlib.lines as mlines /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib-0.98.5-py2.5-macosx-10.3.egg/matplotlib/image.py in () 17 # For clarity, names from _image are given explicitly in this module: 18 from matplotlib import _image ---> 19 from matplotlib import _png 20 21 # For user convenience, the names from _image are also imported into ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib-0.98.5-py2.5-macosx-10.3.egg/matplotlib/_png.so, 2): Library not loaded: /usr/local/lib/libpng12.0.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/matplotlib-0.98.5-py2.5-macosx-10.3.egg/matplotlib/_png.so Reason: image not found In [2]: -- SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada. The future of the web can't happen without you. Join us at MIX09 to help pave the way to the Next Web now. Learn more and register at http://ad.doubleclick.net/clk;208669438;13503038;i?h
[Matplotlib-users] Need some help adjusting placement of colorbar in basemap-derived graphic
Hi All, I'm very new to Matplotlib and am having some trouble getting a colorbar to be positioned and sized I want it to. A big part of the problem is that I have adapted several examples from the Cookbook and Gallery, just to see if I could roughly approximate what I want to see, and now am having trouble integrating the different pieces. Specifically, I can't seem to resolve when to use add_subplot vs. add_axes. Below are 2 examples of code. The first one shows correct layout of a data figure and a separate colorbar below it. The colorbar is the correct size, and is located in the right spot. The second example has the correct data mapped in it using the basemap module, but I cannot get the colorbar to move up closer to the figure, or to shrink it. Could someone advise me on this? I've looked at the "Artist tutorial", and although it is very well written, I'm still not sure how to get this done. Thanks in advance, Roger - Example 1: #! /usr/bin/python import matplotlib.pyplot as plt import numpy as np from numpy.random import randn from matplotlib import mpl # Make plot with horizontal colorbar fig = plt.figure(figsize=(7,8)) ax = fig.add_subplot(111) # 'add_axes' for color bar ax1 = fig.add_axes([0.25, .07, 0.5, 0.03]) # [x_loc, y_loc, x_size, y_size] data = np.clip(randn(250, 250), -1, 1) # DATA FOR SQUARE FIG ax.imshow(data, interpolation='nearest') # DRAW DATA IN SQUARE FIG ax.set_title('Monthly PCP percentiles for 9-2008') ### Colorbar Settings cmap = mpl.cm.cool norm = mpl.colors.Normalize(vmin=0.0, vmax=1.0) cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, norm=norm, orientation='horizontal') cb1.set_label('percentile') plt.show() fig.savefig('test.png') Example 2: #! /usr/bin/python """taken from geos_demo_2.py""" from PIL import Image from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib from matplotlib import mpl import matplotlib.pyplot as plt from matplotlib.image import pil_to_array plot_name = 'hydro_demo.png' overlay_color = 'black' # read in jpeg image to rgb array pilImage = Image.open('wms_mapser.png') #data = asarray(pilImage) data = pil_to_array(pilImage) data = data[:, :, :] # get data from RGB channels of image # define data region and projection parameters ll_lon = -125 ll_lat = 39 ur_lon = -108 ur_lat = 54 lon_0 = 0 fig = plt.figure(figsize=(7,8)) #ax = fig.add_axes((0.1,0.1,0.8,0.8)) ax = fig.add_axes((.1,0.1,0.8,0.8)) # create Basemap instance for cylindrical equidistant projection, htdro image domain m = Basemap(projection='cyl', lon_0=lon_0, llcrnrlon=ll_lon, llcrnrlat=ll_lat, urcrnrlon=ur_lon, urcrnrlat=ur_lat, suppress_ticks=False) # add data cmap = mpl.cm.cool m.imshow(data, cmap, interpolation=None) plt.clim(0, 1) # add a colobar plt.colorbar(orientation='horizontal') # add timestamp and save fig = plt.gcf() # ADD FIGURE TEXT fig.text(x=0.5, y=0.1, s='percentile', fontsize=10, ) fig.set_size_inches((7,7)) # ADD A FIGURE TITLE plt.title('Monthly PCP percentiles for 9-2008',y=1.05,fontsize=12) plt.show() #fig.savefig(plot_name) #print 'Plot saved to %s' % (plot_name) -- SF.Net email is Sponsored by MIX09, March 18-20, 2009 in Las Vegas, Nevada. The future of the web can't happen without you. Join us at MIX09 to help pave the way to the Next Web now. Learn more and register at http://ad.doubleclick.net/clk;208669438;13503038;i?http://2009.visitmix.com/___ Matplotlib-users mailing list Matplotlib-users@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/matplotlib-users
Re: [Matplotlib-users] Need some help adjusting placement of colorbar in basemap-derived graphic
Roger André wrote: > Hi All, > > I'm very new to Matplotlib and am having some trouble getting a > colorbar to be positioned and sized I want it to. A big part of the > problem is that I have adapted several examples from the Cookbook and > Gallery, just to see if I could roughly approximate what I want to > see, and now am having trouble integrating the different pieces. > Specifically, I can't seem to resolve when to use add_subplot vs. > add_axes. Below are 2 examples of code. The first one shows correct > layout of a data figure and a separate colorbar below it. The > colorbar is the correct size, and is located in the right spot. The > second example has the correct data mapped in it using the basemap > module, but I cannot get the colorbar to move up closer to the figure, > or to shrink it. Could someone advise me on this? I've looked at the > "Artist tutorial", and although it is very well written, I'm still not > sure how to get this done . > > Thanks in advance, > > Roger Roger: I usually explicity two separate axes instances, one for the plot and one for the colorbar. The location of the axes always takes a bit of tweaking to get right. Here's an example: from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np # create figure instance. fig = plt.figure(figsize=(8,8)) # create an axes instance, leaving room for colorbars on right and bottom. ax = fig.add_axes([0.05,0.15,0.8,0.8]) # color on bottom # set up orthographic map projection with # perspective of satellite looking down at 50N, 100W. # use low resolution coastlines. map = Basemap(projection='ortho',lat_0=50,lon_0=-100,resolution='c') # draw coastlines, country boundaries, fill continents. map.drawcoastlines() # draw the edge of the map projection region (the projection limb) map.drawmapboundary() # draw lat/lon grid lines every 30 degrees. map.drawmeridians(np.arange(0,360,30)) map.drawparallels(np.arange(-90,90,30)) # make up some data on a regular lat/lon grid. nlats = 73; nlons = 145; delta = 2.*np.pi/(nlons-1) lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) lons = (delta*np.indices((nlats,nlons))[1,:,:]) wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons)) mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.) # compute native map projection coordinates of lat/lon grid. x, y = map(lons*180./np.pi, lats*180./np.pi) # contour data over the map. cs = map.contourf(x,y,wave+mean,15) # get axes bounds. pos = ax.get_position() l, b, w, h = pos.bounds # create axes instance for colorbar on right. cax = plt.axes([l+w+0.03, b, 0.04, h]) # draw colorbar on right. plt.colorbar(cax=cax,orientation='vertical') # create axes instance for colorbar on bottom. cax = plt.axes([l, b-0.07, w, 0.04]) # draw colorbar on bottom. plt.colorbar(cax=cax,orientation='horizontal') plt.show() HTH, -Jeff > - > > Example 1: > > #! /usr/bin/python > > import matplotlib.pyplot as plt > import numpy as np > from numpy.random import randn > from matplotlib import mpl > > # Make plot with horizontal colorbar > > fig = plt.figure(figsize=(7,8)) > ax = fig.add_subplot(111) > > # 'add_axes' for color bar > ax1 = fig.add_axes([0.25, .07, 0.5, 0.03]) # [x_loc, y_loc, x_size, > y_size] > > data = np.clip(randn(250, 250), -1, 1) # DATA FOR SQUARE FIG > ax.imshow(data, interpolation='nearest') # DRAW DATA IN SQUARE FIG > > ax.set_title('Monthly PCP percentiles for 9-2008') > > ### Colorbar Settings > cmap = mpl.cm.cool > norm = mpl.colors.Normalize(vmin=0.0, vmax=1.0) > cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, norm=norm, > orientation='horizontal') > cb1.set_label('percentile') > > > plt.show() > fig.savefig('test.png') > > > Example 2: > > #! /usr/bin/python > > """taken from geos_demo_2.py""" > > from PIL import Image > from mpl_toolkits.basemap import Basemap > import numpy as np > import matplotlib > from matplotlib import mpl > import matplotlib.pyplot as plt > from matplotlib.image import pil_to_array > > plot_name = 'hydro_demo.png' > overlay_color = 'black' > > # read in jpeg image to rgb array > pilImage = Image.open('wms_mapser.png') > > #data = asarray(pilImage) > data = pil_to_array(pilImage) > data = data[:, :, :] # get data from RGB channels of image > > # define data region and projection parameters > ll_lon = -125 > ll_lat = 39 > ur_lon = -108 > ur_lat = 54 > lon_0 = 0 > > > fig = plt.figure(figsize=(7,8)) > #ax = fig.add_axes((0.1,0.1,0.8,0.8)) > ax = fig.add_axes((.1,0.1,0.8,0.8)) > > # create Basemap instance for cylindrical equidistant projection, > htdro image domain > m = Basemap(projection='cyl', lon_0=lon_0, llcrnrlon=ll_lon, > llcrnrlat=ll_lat, urcrnrlon=ur_lon, > urcrnrlat=ur_lat, suppress_ticks=False) > > # add data > cmap = mpl.cm.cool > m.imshow(data, cmap, interpolation=None) > plt.clim(0, 1) > > # add
Re: [Matplotlib-users] Need some help adjusting placement of colorbar in basemap-derived graphic
Thanks Jeff, I'll study your code and will see if I can adapt it for my use. Great tool also, Roger -- On Fri, Dec 12, 2008 at 3:20 PM, Jeff Whitaker wrote: > Roger André wrote: > >> Hi All, >> >> I'm very new to Matplotlib and am having some trouble getting a colorbar >> to be positioned and sized I want it to. A big part of the problem is that >> I have adapted several examples from the Cookbook and Gallery, just to see >> if I could roughly approximate what I want to see, and now am having trouble >> integrating the different pieces. Specifically, I can't seem to resolve >> when to use add_subplot vs. add_axes. Below are 2 examples of code. The >> first one shows correct layout of a data figure and a separate colorbar >> below it. The colorbar is the correct size, and is located in the right >> spot. The second example has the correct data mapped in it using the >> basemap module, but I cannot get the colorbar to move up closer to the >> figure, or to shrink it. Could someone advise me on this? I've looked at >> the "Artist tutorial", and although it is very well written, I'm still not >> sure how to get this done . >> >> Thanks in advance, >> >> Roger >> > > Roger: I usually explicity two separate axes instances, one for the plot > and one for the colorbar. The location of the axes always takes a bit of > tweaking to get right. Here's an example: > > from mpl_toolkits.basemap import Basemap > import matplotlib.pyplot as plt > import numpy as np > # create figure instance. > fig = plt.figure(figsize=(8,8)) > # create an axes instance, leaving room for colorbars on right and bottom. > ax = fig.add_axes([0.05,0.15,0.8,0.8]) # color on bottom > # set up orthographic map projection with > # perspective of satellite looking down at 50N, 100W. > # use low resolution coastlines. > map = Basemap(projection='ortho',lat_0=50,lon_0=-100,resolution='c') > # draw coastlines, country boundaries, fill continents. > map.drawcoastlines() > # draw the edge of the map projection region (the projection limb) > map.drawmapboundary() > # draw lat/lon grid lines every 30 degrees. > map.drawmeridians(np.arange(0,360,30)) > map.drawparallels(np.arange(-90,90,30)) > # make up some data on a regular lat/lon grid. > nlats = 73; nlons = 145; delta = 2.*np.pi/(nlons-1) > lats = (0.5*np.pi-delta*np.indices((nlats,nlons))[0,:,:]) > lons = (delta*np.indices((nlats,nlons))[1,:,:]) > wave = 0.75*(np.sin(2.*lats)**8*np.cos(4.*lons)) > mean = 0.5*np.cos(2.*lats)*((np.sin(2.*lats))**2 + 2.) > # compute native map projection coordinates of lat/lon grid. > x, y = map(lons*180./np.pi, lats*180./np.pi) > # contour data over the map. > cs = map.contourf(x,y,wave+mean,15) > # get axes bounds. > pos = ax.get_position() > l, b, w, h = pos.bounds > # create axes instance for colorbar on right. > cax = plt.axes([l+w+0.03, b, 0.04, h]) > # draw colorbar on right. > plt.colorbar(cax=cax,orientation='vertical') > # create axes instance for colorbar on bottom. > cax = plt.axes([l, b-0.07, w, 0.04]) > # draw colorbar on bottom. > plt.colorbar(cax=cax,orientation='horizontal') > plt.show() > > HTH, > > -Jeff > >> - >> >> Example 1: >> >> #! /usr/bin/python >> >> import matplotlib.pyplot as plt >> import numpy as np >> from numpy.random import randn >> from matplotlib import mpl >> >> # Make plot with horizontal colorbar >> >> fig = plt.figure(figsize=(7,8)) >> ax = fig.add_subplot(111) >> >> # 'add_axes' for color bar >> ax1 = fig.add_axes([0.25, .07, 0.5, 0.03]) # [x_loc, y_loc, x_size, >> y_size] >> >> data = np.clip(randn(250, 250), -1, 1) # DATA FOR SQUARE FIG >> ax.imshow(data, interpolation='nearest') # DRAW DATA IN SQUARE FIG >> >> ax.set_title('Monthly PCP percentiles for 9-2008') >> >> ### Colorbar Settings >> cmap = mpl.cm.cool >> norm = mpl.colors.Normalize(vmin=0.0, vmax=1.0) >> cb1 = mpl.colorbar.ColorbarBase(ax1, cmap=cmap, norm=norm, >> orientation='horizontal') >> cb1.set_label('percentile') >> >> >> plt.show() >> fig.savefig('test.png') >> >> >> >> Example 2: >> >> #! /usr/bin/python >> >> """taken from geos_demo_2.py""" >> >> from PIL import Image >> from mpl_toolkits.basemap import Basemap >> import numpy as np >> import matplotlib >> from matplotlib import mpl >> import matplotlib.pyplot as plt >> from matplotlib.image import pil_to_array >> >> plot_name = 'hydro_demo.png' >> overlay_color = 'black' >> >> # read in jpeg image to rgb array >> pilImage = Image.open('wms_mapser.png') >> >> #data = asarray(pilImage) >> data = pil_to_array(pilImage) >> data = data[:, :, :] # get data from RGB channels of image >> >> # define data region and projection parameters >> ll_lon = -125 >> ll_lat = 39 >> ur_lon = -108 >> ur_lat = 54 >> lon_0 = 0 >> >> >> fig = plt.figure(figsize=(7,8)) >> #ax = fig.add_axes((0.1,0.1,0.8,0.8)) >> ax = fig.add_axes((.1,0.1,0.8,0.8)) >> >> # crea