You are on page 1of 52

Pyplot animation example. The method shown here is only for very simple, low-performance use.

For more demanding applications, look at the animation module and the examples that use it. """ import matplotlib.pyplot as plt import numpy as np x = np.arange(6) y = np.arange(5) z = x * y[:,np.newaxis] for i in xrange(5): if i==0: p = plt.imshow(z) fig = plt.gcf() plt.clim() # clamp the color limits plt.title("Boring slide show") else: z = z + 2 p.set_data(z) print "step", i plt.pause(0.5)

"""Produce custom labelling for a colorbar. Contributed by Scott Sinclair """ import matplotlib.pyplot as plt import numpy as np from numpy.random import randn # Make plot with vertical (default) colorbar fig = plt.figure() ax = fig.add_subplot(111) data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, interpolation='nearest') ax.set_title('Gaussian noise with vertical colorbar') # Add colorbar, make sure to specify tick locations to match desired ticklabels cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) cbar.ax.set_yticklabels(['< -1', '0', '> 1'])# vertically oriented colorbar # Make plot with horizontal colorbar fig = plt.figure() ax = fig.add_subplot(111)

data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, interpolation='nearest') ax.set_title('Gaussian noise with horizontal colorbar') cbar = fig.colorbar(cax, ticks=[-1, 0, 1], orientation='horizontal') cbar.ax.set_xticklabels(['Low', 'Medium', 'High'])# horizontal colorbar plt.show()

#!/usr/bin/env python """ Compute the coherence of two signals """ import numpy as np import matplotlib.pyplot as plt # make a little extra space between the subplots plt.subplots_adjust(wspace=0.5) dt = 0.01 t = np.arange(0, 30, dt) nse1 = np.random.randn(len(t)) nse2 = np.random.randn(len(t)) r = np.exp(-t/0.05) cnse1 = np.convolve(nse1, r, mode='same')*dt cnse2 = np.convolve(nse2, r, mode='same')*dt

# white noise 1 # white noise 2 # colored noise 1 # colored noise 2

# two signals with a coherent part and a random part s1 = 0.01*np.sin(2*np.pi*10*t) + cnse1 s2 = 0.01*np.sin(2*np.pi*10*t) + cnse2 plt.subplot(211) plt.plot(t, s1, 'b-', t, s2, 'g-') plt.xlim(0,5) plt.xlabel('time') plt.ylabel('s1 and s2') plt.grid(True) plt.subplot(212) cxy, f = plt.cohere(s1, s2, 256, 1./dt) plt.ylabel('coherence') plt.show()

#!/usr/bin/env python """ Illustrate simple contour plotting, contours on an image with a colorbar for the contours, and labelled contours. See also contour_image.py. """ import matplotlib import numpy as np

import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' delta = 0.025 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) # difference of Gaussians Z = 10.0 * (Z2 - Z1)

# Create a simple contour plot with labels using default colors. The # inline argument to clabel will control whether the labels are draw # over the line segments of the contour, removing the lines beneath # the label plt.figure() CS = plt.contour(X, Y, Z) plt.clabel(CS, inline=1, fontsize=10) plt.title('Simplest default with labels') # You can force all the contours to be the same color. plt.figure() CS = plt.contour(X, Y, Z, 6, colors='k', # negative contours will be dashed by default ) plt.clabel(CS, fontsize=9, inline=1) plt.title('Single color - negative contours dashed') # You can set negative contours to be solid instead of dashed: matplotlib.rcParams['contour.negative_linestyle'] = 'solid' plt.figure() CS = plt.contour(X, Y, Z, 6, colors='k', # negative contours will be dashed by default ) plt.clabel(CS, fontsize=9, inline=1) plt.title('Single color - negative contours solid') # And you can manually specify the colors of the contour plt.figure() CS = plt.contour(X, Y, Z, 6, linewidths=np.arange(.5, 4, .5), colors=('r', 'green', 'blue', (1,1,0), '#afeeee', '0.5') ) plt.clabel(CS, fontsize=9, inline=1) plt.title('Crazy lines') # Or you can use a colormap to specify the colors; the default

# colormap will be used for the contour lines plt.figure() im = plt.imshow(Z, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=(-3,3,-2,2)) levels = np.arange(-1.2, 1.6, 0.2) CS = plt.contour(Z, levels, origin='lower', linewidths=2, extent=(-3,3,-2,2)) #Thicken the zero contour. zc = CS.collections[6] plt.setp(zc, linewidth=4) plt.clabel(CS, levels[1::2], inline=1, fmt='%1.1f', fontsize=14) # label every second level

# make a colorbar for the contour lines CB = plt.colorbar(CS, shrink=0.8, extend='both') plt.title('Lines with colorbar') #plt.hot() # Now change the colormap for the contour lines and colorbar plt.flag() # We can still add a colorbar for the image, too. CBI = plt.colorbar(im, orientation='horizontal', shrink=0.8) # This makes the original colorbar look a bit out of place, # so let's improve its position. l,b,w,h = plt.gca().get_position().bounds ll,bb,ww,hh = CB.ax.get_position().bounds CB.ax.set_position([ll, b+0.1*h, ww, h*0.8]) plt.show()

#!/usr/bin/env python ''' Test combinations of contouring, filled contouring, and image plotting. For contour labelling, see contour_demo.py. The emphasis in this demo is on showing how to make contours register correctly on images, and on how to get both of them oriented as desired. In particular, note the usage of the "origin" and "extent" keyword arguments to imshow and contour. ''' from pylab import * #Default delta is large because that makes it fast, and it illustrates # the correct registration between image and contours. delta = 0.5

extent = (-3,4,-4,3) x = arange(-3.0, 4.001, delta) y = arange(-4.0, 3.001, delta) X, Y = meshgrid(x, y) Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = (Z1 - Z2) * 10 levels = arange(-2.0, 1.601, 0.4) # Boost the upper limit to avoid truncation # errors. figure() subplot(2,2,1) cset1 = contourf(X, Y, Z, levels, cmap=cm.get_cmap('jet', len(levels)-1), ) # It is not necessary, but for the colormap, we need only the # number of levels minus 1. To avoid discretization error, use # either this number or a large number such as the default (256). #If we want lines as well as filled regions, we need to call # contour separately; don't try to change the edgecolor or edgewidth # of the polygons in the collections returned by contourf. # Use levels output from previous call to guarantee they are the same. cset2 = contour(X, Y, Z, cset1.levels, colors = 'k', hold='on') # We don't really need dashed contour lines to indicate negative # regions, so let's turn them off. for c in cset2.collections: c.set_linestyle('solid') # It is easier here to make a separate call to contour than # to set up an array of colors and linewidths. # We are making a thick green line as a zero contour. # Specify the zero level as a tuple with only 0 in it. cset3 = contour(X, Y, Z, (0,), colors = 'g', linewidths = 2, hold='on') title('Filled contours') colorbar(cset1) #hot() subplot(2,2,2) imshow(Z, extent=extent) v = axis() contour(Z, levels, hold='on', colors = 'k', origin='upper', extent=extent) axis(v) title("Image, origin 'upper'")

subplot(2,2,3) imshow(Z, origin='lower', extent=extent) v = axis() contour(Z, levels, hold='on', colors = 'k', origin='lower', extent=extent) axis(v) title("Image, origin 'lower'") subplot(2,2,4) # We will use the interpolation "nearest" here to show the actual # image pixels. # Note that the contour lines don't extend to the edge of the box. # This is intentional. The Z values are defined at the center of each # image pixel (each color block on the following subplot), so the # domain that is contoured does not extend beyond these pixel centers. im = imshow(Z, interpolation='nearest', extent=extent) v = axis() contour(Z, levels, hold='on', colors = 'k', origin='image', extent=extent) axis(v) ylim = get(gca(), 'ylim') setp(gca(), ylim=ylim[::-1]) title("Image, origin from rc, reversed y-axis") colorbar(im) show()

#!/usr/bin/env python from pylab import * origin = 'lower' #origin = 'upper' delta = 0.025 x = y = arange(-3.0, 3.01, delta) X, Y = meshgrid(x, y) Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10 * (Z1 - Z2) nr, nc = Z.shape # put NaNs in one corner: Z[-nr//6:, -nc//6:] = nan # contourf will convert these to masked Z = ma.array(Z) # mask another corner: Z[:nr//6, :nc//6] = ma.masked # mask a circle in the middle:

interior = sqrt((X**2) + (Y**2)) < 0.5 Z[interior] = ma.masked # We are using automatic selection of contour levels; # this is usually not such a good idea, because they don't # occur on nice boundaries, but we do it here for purposes # of illustration. CS = contourf(X, Y, Z, 10, # [-1, -0.1, 0, 0.1], #alpha=0.5, cmap=cm.bone, origin=origin) # # # # Note that in the following, we explicitly pass in a subset of the contour levels used for the filled contours. Alternatively, We could pass in additional levels to provide extra resolution, or leave out the levels kwarg to use all of the original levels.

CS2 = contour(CS, levels=CS.levels[::2], colors = 'r', origin=origin, hold='on') title('Nonsense (3 masked regions)') xlabel('word length anomaly') ylabel('sentence length anomaly') # Make a colorbar for the ContourSet returned by the contourf call. cbar = colorbar(CS) cbar.ax.set_ylabel('verbosity coefficient') # Add the contour line levels to the colorbar cbar.add_lines(CS2) figure() # Now make a contour plot with the levels specified, # and with the colormap generated automatically from a list # of colors. levels = [-1.5, -1, -0.5, 0, 0.5, 1] CS3 = contourf(X, Y, Z, levels, colors = ('r', 'g', 'b'), origin=origin, extend='both') # Our data range extends outside the range of levels; make # data below the lowest contour level yellow, and above the # highest level cyan: CS3.cmap.set_under('yellow') CS3.cmap.set_over('cyan') CS4 = contour(X, Y, Z, levels, colors = ('k',), linewidths = (3,), origin = origin) title('Listed colors (3 masked regions)') clabel(CS4, fmt = '%2.1f', colors = 'w', fontsize=14) # Notice that the colorbar command gets all the information it

# needs from the ContourSet object, CS3. colorbar(CS3) show()

''' Demonstrate use of a log color scale in contourf ''' from matplotlib import pyplot as P import numpy as np from numpy import ma from matplotlib import colors, ticker from matplotlib.mlab import bivariate_normal N = 100 x = np.linspace(-3.0, 3.0, N) y = np.linspace(-2.0, 2.0, N) X, Y = np.meshgrid(x, y) # # # z A low hump with a spike coming out of the top right. Needs to have z/colour axis on a log scale so we see both hump and spike. linear scale only shows the spike. = (bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) + 0.1 * bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0))

# Put in some negative values (lower left corner) to cause trouble with logs: z[:5, :5] = -1 # The following is not strictly essential, but it will eliminate # a warning. Comment it out to see the warning. z = ma.masked_where(z<= 0, z) # Automatic selection of levels works; setting the # log locator tells contourf to use a log scale: cs = P.contourf(X, Y, z, locator=ticker.LogLocator()) # Alternatively, you can manually set the levels # and the norm: #lev_exp = np.arange(np.floor(np.log10(z.min())-1), # np.ceil(np.log10(z.max())+1)) #levs = np.power(10, lev_exp) #cs = P.contourf(X, Y, z, levs, norm=colors.LogNorm()) #The 'extend' kwarg does not work yet with a log scale. cbar = P.colorbar() P.show()

#!/usr/bin/env python

import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap """ Example: suppose you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, and blue over the top half. Then you would use: cdict = {'red': ((0.0, (0.5, (1.0, 0.0, 0.0), 1.0, 1.0), 1.0, 1.0)), 0.0, 0.0, 1.0, 1.0, 0.0), 0.0), 1.0), 1.0)),

'green': ((0.0, (0.25, (0.75, (1.0, 'blue': ((0.0, (0.5, (1.0,

0.0, 0.0), 0.0, 0.0), 1.0, 1.0))}

If, as in this example, there are no discontinuities in the r, g, and b components, then it is quite simple: the second and third element of each tuple, above, is the same--call it "y". The first element ("x") defines interpolation intervals over the full range of 0 to 1, and it must span that whole range. In other words, the values of x divide the 0-to-1 range into a set of segments, and y gives the end-point color values for each segment. Now consider the green. cdict['green'] is saying that for 0 <= x <= 0.25, y is zero; no green. 0.25 < x <= 0.75, y varies linearly from 0 to 1. x > 0.75, y remains at 1, full green. If there are discontinuities, then it is a little more complicated. Label the 3 elements in each row in the cdict entry for a given color as (x, y0, y1). Then for values of x between x[i] and x[i+1] the color value is interpolated between y1[i] and y0[i+1]. Going back to the cookbook example, look at cdict['red']; because y0 != y1, it is saying that for x from 0 to 0.5, red increases from 0 to 1, but then it jumps down, so that for x from 0.5 to 1, red increases from 0.7 to 1. Green ramps from 0 to 1 as x goes from 0 to 0.5, then jumps back to 0, and ramps back to 1 as x goes from 0.5 to 1. row i: x y0 / row i+1: x y0 y1 Above is an attempt to show that for x in the range x[i] to x[i+1], the interpolation is between y1[i] and y0[i+1]. So, y0[0] and y1[-1] are never used. """ y1 /

cdict1 = {'red':

((0.0, 0.0, 0.0), (0.5, 0.0, 0.1), (1.0, 1.0, 1.0)),

'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': } cdict2 = {'red': ((0.0, 0.0, 0.0), (0.5, 0.0, 1.0), (1.0, 0.1, 1.0)), ((0.0, 0.0, 1.0), (0.5, 0.1, 0.0), (1.0, 0.0, 0.0))

'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': } cdict3 = {'red': ((0.0, 0.0, (0.25,0.0, (0.5, 0.8, (0.75,1.0, (1.0, 0.4, 0.0), 0.0), 1.0), 1.0), 1.0)), 0.0), 0.0), 0.9), 0.0), 0.0)), 0.4), 1.0), 0.8), 0.0), 0.0)) ((0.0, 0.0, 0.1), (0.5, 1.0, 0.0), (1.0, 0.0, 0.0))

'green': ((0.0, 0.0, (0.25,0.0, (0.5, 0.9, (0.75,0.0, (1.0, 0.0, 'blue': ((0.0, 0.0, (0.25,1.0, (0.5, 1.0, (0.75,0.0, (1.0, 0.0,

} # Now we will use this example to illustrate 3 ways of # handling custom colormaps. # First, the most direct and explicit: blue_red1 = LinearSegmentedColormap('BlueRed1', cdict1) # # # # Second, create the map explicitly and register it. Like the first method, this method works with any kind of Colormap, not just a LinearSegmentedColormap:

blue_red2 = LinearSegmentedColormap('BlueRed2', cdict2) plt.register_cmap(cmap=blue_red2) # Third, for LinearSegmentedColormap only, # leave everything to register_cmap: plt.register_cmap(name='BlueRed3', data=cdict3) # optional lut kwarg x = np.arange(0, np.pi, 0.1) y = np.arange(0, 2*np.pi, 0.1) X, Y = np.meshgrid(x,y) Z = np.cos(X) * np.sin(Y) plt.figure(figsize=(10,4)) plt.subplots_adjust(wspace=0.3) plt.subplot(1,3,1) plt.imshow(Z, interpolation='nearest', cmap=blue_red1) plt.colorbar() plt.subplot(1,3,2) cmap = plt.get_cmap('BlueRed2') plt.imshow(Z, interpolation='nearest', cmap=cmap) plt.colorbar() # Now we will set the third cmap as the default. One would # not normally do this in the middle of a script like this; # it is done here just to illustrate the method. plt.rcParams['image.cmap'] = 'BlueRed3' # Also see below for an alternative, particularly for # interactive use. plt.subplot(1,3,3) plt.imshow(Z, interpolation='nearest') plt.colorbar() # # # # # # # # Or as yet another variation, we could replace the rcParams specification *before* the imshow with the following *after* imshow: plt.set_cmap('BlueRed3') This sets the new default *and* sets the colormap of the last image-like item plotted via pyplot, if any.

plt.suptitle('Custom Blue-Red colormaps') plt.show()

import matplotlib.pyplot as plt import numpy as np

import matplotlib.cm as cm import matplotlib.mlab as mlab def smooth1d(x, window_len): # copied from http://www.scipy.org/Cookbook/SignalSmooth s=np.r_[2*x[0]-x[window_len:1:-1],x,2*x[-1]-x[-1:-window_len:-1]] w = np.hanning(window_len) y=np.convolve(w/w.sum(),s,mode='same') return y[window_len-1:-window_len+1] def smooth2d(A, sigma=3): window_len = max(int(sigma), 3)*2+1 A1 = np.array([smooth1d(x, window_len) for x in np.asarray(A)]) A2 = np.transpose(A1) A3 = np.array([smooth1d(x, window_len) for x in A2]) A4 = np.transpose(A3) return A4

class BaseFilter(object): def prepare_image(self, src_image, dpi, pad): ny, nx, depth = src_image.shape #tgt_image = np.zeros([pad*2+ny, pad*2+nx, depth], dtype="d") padded_src = np.zeros([pad*2+ny, pad*2+nx, depth], dtype="d") padded_src[pad:-pad, pad:-pad,:] = src_image[:,:,:] return padded_src#, tgt_image def get_pad(self, dpi): return 0 def __call__(self, im, dpi): pad = self.get_pad(dpi) padded_src = self.prepare_image(im, dpi, pad) tgt_image = self.process_image(padded_src, dpi) return tgt_image, -pad, -pad class OffsetFilter(BaseFilter): def __init__(self, offsets=None): if offsets is None: self.offsets = (0, 0) else: self.offsets = offsets def get_pad(self, dpi): return int(max(*self.offsets)/72.*dpi) def process_image(self, padded_src, dpi): ox, oy = self.offsets a1 = np.roll(padded_src, int(ox/72.*dpi), axis=1) a2 = np.roll(a1, -int(oy/72.*dpi), axis=0)

return a2 class GaussianFilter(BaseFilter): "simple gauss filter" def __init__(self, sigma, alpha=0.5, color=None): self.sigma = sigma self.alpha = alpha if color is None: self.color=(0, 0, 0) else: self.color=color def get_pad(self, dpi): return int(self.sigma*3/72.*dpi) def process_image(self, padded_src, dpi): #offsetx, offsety = int(self.offsets[0]), int(self.offsets[1]) tgt_image = np.zeros_like(padded_src) aa = smooth2d(padded_src[:,:,-1]*self.alpha, self.sigma/72.*dpi) tgt_image[:,:,-1] = aa tgt_image[:,:,:-1] = self.color return tgt_image class DropShadowFilter(BaseFilter): def __init__(self, sigma, alpha=0.3, color=None, offsets=None): self.gauss_filter = GaussianFilter(sigma, alpha, color) self.offset_filter = OffsetFilter(offsets) def get_pad(self, dpi): return max(self.gauss_filter.get_pad(dpi), self.offset_filter.get_pad(dpi)) def process_image(self, padded_src, dpi): t1 = self.gauss_filter.process_image(padded_src, dpi) t2 = self.offset_filter.process_image(t1, dpi) return t2 from matplotlib.colors import LightSource class LightFilter(BaseFilter): "simple gauss filter" def __init__(self, sigma, fraction=0.5): self.gauss_filter = GaussianFilter(sigma, alpha=1) self.light_source = LightSource() self.fraction = fraction #hsv_min_val=0.5,hsv_max_val=0.9, # hsv_min_sat=0.1,hsv_max_sat=0.1) def get_pad(self, dpi): return self.gauss_filter.get_pad(dpi) def process_image(self, padded_src, dpi): t1 = self.gauss_filter.process_image(padded_src, dpi) elevation = t1[:,:,3] rgb = padded_src[:,:,:3]

rgb2 = self.light_source.shade_rgb(rgb, elevation, fraction=self.fraction) tgt = np.empty_like(padded_src) tgt[:,:,:3] = rgb2 tgt[:,:,3] = padded_src[:,:,3] return tgt

class GrowFilter(BaseFilter): "enlarge the area" def __init__(self, pixels, color=None): self.pixels = pixels if color is None: self.color=(1, 1, 1) else: self.color=color def __call__(self, im, dpi): pad = self.pixels ny, nx, depth = im.shape new_im = np.empty([pad*2+ny, pad*2+nx, depth], dtype="d") alpha = new_im[:,:,3] alpha.fill(0) alpha[pad:-pad, pad:-pad] = im[:,:,-1] alpha2 = np.clip(smooth2d(alpha, self.pixels/72.*dpi) * 5, 0, 1) new_im[:,:,-1] = alpha2 new_im[:,:,:-1] = self.color offsetx, offsety = -pad, -pad return new_im, offsetx, offsety from matplotlib.artist import Artist class FilteredArtistList(Artist): """ A simple container to draw filtered artist. """ def __init__(self, artist_list, filter): self._artist_list = artist_list self._filter = filter Artist.__init__(self) def draw(self, renderer): renderer.start_rasterizing() renderer.start_filter() for a in self._artist_list: a.draw(renderer) renderer.stop_filter(self._filter) renderer.stop_rasterizing()

import matplotlib.transforms as mtransforms def filtered_text(ax): # mostly copied from contour_demo.py # prepare image delta = 0.025 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) # difference of Gaussians Z = 10.0 * (Z2 - Z1) # draw im = ax.imshow(Z, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=(-3,3,-2,2)) levels = np.arange(-1.2, 1.6, 0.2) CS = ax.contour(Z, levels, origin='lower', linewidths=2, extent=(-3,3,-2,2)) ax.set_aspect("auto") # contour label cl = ax.clabel(CS, levels[1::2], inline=1, fmt='%1.1f', fontsize=11) # label every second level

# change clable color to black from matplotlib.patheffects import Normal for t in cl: t.set_color("k") t.set_path_effects([Normal()]) # to force TextPath (i.e., same font in all backends) # Add white glows to improve visibility of labels. white_glows = FilteredArtistList(cl, GrowFilter(3)) ax.add_artist(white_glows) white_glows.set_zorder(cl[0].get_zorder()-0.1) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) def drop_shadow_line(ax): # copyed from examples/misc/svg_filter_line.py # draw lines l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-", mec="b", mfc="w", lw=5, mew=3, ms=10, label="Line 1") l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-", mec="r", mfc="w", lw=5, mew=3, ms=10, label="Line 1")

gauss = DropShadowFilter(4) for l in [l1, l2]: # draw shadows with same lines with slight offset. xx = l.get_xdata() yy = l.get_ydata() shadow, = ax.plot(xx, yy) shadow.update_from(l) # offset transform ot = mtransforms.offset_copy(l.get_transform(), ax.figure, x=4.0, y=-6.0, units='points') shadow.set_transform(ot) # adjust zorder of the shadow lines so that it is drawn below the # original lines shadow.set_zorder(l.get_zorder()-0.5) shadow.set_agg_filter(gauss) shadow.set_rasterized(True) # to support mixed-mode renderers

ax.set_xlim(0., 1.) ax.set_ylim(0., 1.) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False)

def drop_shadow_patches(ax): # copyed from barchart_demo.py N = 5 menMeans = (20, 35, 30, 35, 27) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars rects1 = ax.bar(ind, menMeans, width, color='r', ec="w", lw=2) womenMeans = (25, 32, 34, 20, 25) rects2 = ax.bar(ind+width+0.1, womenMeans, width, color='y', ec="w", lw=2) #gauss = GaussianFilter(1.5, offsets=(1,1), ) gauss = DropShadowFilter(5, offsets=(1,1), ) shadow = FilteredArtistList(rects1+rects2, gauss) ax.add_artist(shadow) shadow.set_zorder(rects1[0].get_zorder()-0.1)

ax.set_xlim(ind[0]-0.5, ind[-1]+1.5) ax.set_ylim(0, 40) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) def light_filter_pie(ax): fracs = [15,30,45, 10] explode=(0, 0.05, 0, 0) pies = ax.pie(fracs, explode=explode) ax.patch.set_visible(True) light_filter = LightFilter(9) for p in pies[0]: p.set_agg_filter(light_filter) p.set_rasterized(True) # to support mixed-mode renderers p.set(ec="none", lw=2) gauss = DropShadowFilter(9, offsets=(3,4), alpha=0.7) shadow = FilteredArtistList(pies[0], gauss) ax.add_artist(shadow) shadow.set_zorder(pies[0][0].get_zorder()-0.1) if 1: plt.figure(1, figsize=(6, 6)) plt.subplots_adjust(left=0.05, right=0.95) ax = plt.subplot(221) filtered_text(ax) ax = plt.subplot(222) drop_shadow_line(ax) ax = plt.subplot(223) drop_shadow_patches(ax) ax = plt.subplot(224) ax.set_aspect(1) light_filter_pie(ax) ax.set_frame_on(True) plt.show()

import matplotlib.pyplot as plt import numpy as np from matplotlib.collections import EllipseCollection x = np.arange(10) y = np.arange(15) X, Y = np.meshgrid(x, y)

XY = np.hstack((X.ravel()[:,np.newaxis], Y.ravel()[:,np.newaxis])) ww = X/10.0 hh = Y/15.0 aa = X*9 ax = plt.subplot(1,1,1) ec = EllipseCollection( ww, hh, aa, units='x', offsets=XY, transOffset=ax.transData) ec.set_array((X+Y).ravel()) ax.add_collection(ec) ax.autoscale_view() ax.set_xlabel('X') ax.set_ylabel('y') cbar = plt.colorbar(ec) cbar.set_label('X+Y') plt.show()

from pylab import figure, show, rand from matplotlib.patches import Ellipse NUM = 250 ells = [Ellipse(xy=rand(2)*10, width=rand(), height=rand(), angle=rand()*360) for i in xrange(NUM)] fig = figure() ax = fig.add_subplot(111, aspect='equal') for e in ells: ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_alpha(rand()) e.set_facecolor(rand(3)) ax.set_xlim(0, 10) ax.set_ylim(0, 10) show()

#!/usr/bin/env python from matplotlib.font_manager import FontProperties from pylab import * def f(t): s1 = cos(2*pi*t) e1 = exp(-t) return multiply(s1,e1)

t1 = arange(0.0, 5.0, 0.1) t2 = arange(0.0, 5.0, 0.02) t3 = arange(0.0, 2.0, 0.01) subplot(121) plot(t1, f(t1), 'bo', t2, f(t2), 'k') title('subplot 1') ylabel('Damped oscillation') suptitle('This is a somewhat long figure title', fontsize=16) subplot(122) plot(t3, cos(2*pi*t3), 'r--') xlabel('time (s)') title('subplot 2') ylabel('Undamped') show()

#!/usr/bin/env python import matplotlib.mlab as mlab from matplotlib.pyplot import figure, show import numpy as np x = np.arange(0.0, 2, 0.01) y1 = np.sin(2*np.pi*x) y2 = 1.2*np.sin(4*np.pi*x) fig ax1 ax2 ax3 = = = = figure() fig.add_subplot(311) fig.add_subplot(312, sharex=ax1) fig.add_subplot(313, sharex=ax1)

ax1.fill_between(x, 0, y1) ax1.set_ylabel('between y1 and 0') ax2.fill_between(x, y1, 1) ax2.set_ylabel('between y1 and 1') ax3.fill_between(x, y1, y2) ax3.set_ylabel('between y1 and y2') ax3.set_xlabel('x') # now fill between y1 and y2 where a logical condition is met. Note # this is different than calling # fill_between(x[where], y1[where],y2[where] # because of edge effects over multiple contiguous regions. fig = figure() ax = fig.add_subplot(211) ax.plot(x, y1, x, y2, color='black') ax.fill_between(x, y1, y2, where=y2>=y1, facecolor='green', interpolate=True) ax.fill_between(x, y1, y2, where=y2<=y1, facecolor='red', interpolate=True) ax.set_title('fill between where')

# Test support for masked arrays. y2 = np.ma.masked_greater(y2, 1.0) ax1 = fig.add_subplot(212, sharex=ax) ax1.plot(x, y1, x, y2, color='black') ax1.fill_between(x, y1, y2, where=y2>=y1, facecolor='green', interpolate=True) ax1.fill_between(x, y1, y2, where=y2<=y1, facecolor='red', interpolate=True) ax1.set_title('Now regions with y2>1 are masked') # # # # This example illustrates a problem; because of the data gridding, there are undesired unfilled triangles at the crossover points. A brute-force solution would be to interpolate all arrays to a very fine grid before plotting.

# show how to use transforms to create axes spans where a certain condition is satisfied fig = figure() ax = fig.add_subplot(111) y = np.sin(4*np.pi*x) ax.plot(x, y, color='black') # use the data coordinates for the x-axis and the axes coordinates for the yaxis import matplotlib.transforms as mtransforms trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes) theta = 0.9 ax.axhline(theta, color='green', lw=2, alpha=0.5) ax.axhline(-theta, color='red', lw=2, alpha=0.5) ax.fill_between(x, 0, 1, where=y>theta, facecolor='green', alpha=0.5, transform=trans) ax.fill_between(x, 0, 1, where=y<-theta, facecolor='red', alpha=0.5, transform=trans)

show()

#!/usr/bin/env python from pylab import * theta = arange(0,8*pi,0.1) a=1 b=.2 for dt in arange(0,2*pi,pi/2.0): x = a*cos( theta+dt )*exp(b*theta) y = a*sin( theta+dt )*exp(b*theta) dt = dt+pi/4.0 x2 = a*cos( theta+dt )*exp(b*theta) y2 = a*sin( theta+dt )*exp(b*theta)

xf = concatenate( (x,x2[::-1]) ) yf = concatenate( (y,y2[::-1]) ) p1=fill(xf,yf) show()

#!/usr/bin/env python from pylab import * from matplotlib.dates import DateFormatter, WeekdayLocator, HourLocator, \ DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo, candlestick,\ plot_day_summary, candlestick2 # (Year, month, day) tuples suffice as args for quotes_historical_yahoo date1 = ( 2004, 2, 1) date2 = ( 2004, 4, 12 ) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # Eg, Jan 12 dayFormatter = DateFormatter('%d') # Eg, 12 quotes = quotes_historical_yahoo('INTC', date1, date2) if len(quotes) == 0: raise SystemExit fig = figure() fig.subplots_adjust(bottom=0.2) ax = fig.add_subplot(111) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) candlestick(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() setp( gca().get_xticklabels(), rotation=45, horizontalalignment='right') show()

import import import import import import import import

datetime numpy as np matplotlib.colors as colors matplotlib.finance as finance matplotlib.dates as mdates matplotlib.ticker as mticker matplotlib.mlab as mlab matplotlib.pyplot as plt

import matplotlib.font_manager as font_manager startdate = datetime.date(2006,1,1) today = enddate = datetime.date.today() ticker = 'SPY' fh = finance.fetch_historical_yahoo(ticker, startdate, enddate) # a numpy record array with fields: date, open, high, low, close, volume, adj_close) r = mlab.csv2rec(fh); fh.close() r.sort() def moving_average(x, n, type='simple'): """ compute an n period moving average. type is 'simple' | 'exponential' """ x = np.asarray(x) if type=='simple': weights = np.ones(n) else: weights = np.exp(np.linspace(-1., 0., n)) weights /= weights.sum() a = np.convolve(x, weights, mode='full')[:len(x)] a[:n] = a[n] return a def relative_strength(prices, n=14): """ compute the n period relative strength indicator http://stockcharts.com/school/doku.php?id=chart_school:glossary_r#relativestr engthindex http://www.investopedia.com/terms/r/rsi.asp """ deltas = np.diff(prices) seed = deltas[:n+1] up = seed[seed>=0].sum()/n down = -seed[seed<0].sum()/n rs = up/down rsi = np.zeros_like(prices) rsi[:n] = 100. - 100./(1.+rs) for i in range(n, len(prices)): delta = deltas[i-1] # cause the diff is 1 shorter if delta>0:

upval = downval else: upval = downval

delta = 0. 0. = -delta

up = (up*(n-1) + upval)/n down = (down*(n-1) + downval)/n rs = up/down rsi[i] = 100. - 100./(1.+rs) return rsi def moving_average_convergence(x, nslow=26, nfast=12): """ compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg' return value is emaslow, emafast, macd which are len(x) arrays """ emaslow = moving_average(x, nslow, type='exponential') emafast = moving_average(x, nfast, type='exponential') return emaslow, emafast, emafast - emaslow plt.rc('axes', grid=True) plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5) textsize = 9 left, width = 0.1, 0.8 rect1 = [left, 0.7, width, 0.2] rect2 = [left, 0.3, width, 0.4] rect3 = [left, 0.1, width, 0.2] fig = plt.figure(facecolor='white') axescolor = '#f6f6f6' # the axies background color ax1 = fig.add_axes(rect1, axisbg=axescolor) #left, bottom, width, height ax2 = fig.add_axes(rect2, axisbg=axescolor, sharex=ax1) ax2t = ax2.twinx() ax3 = fig.add_axes(rect3, axisbg=axescolor, sharex=ax1)

### plot the relative strength indicator prices = r.adj_close rsi = relative_strength(prices) fillcolor = 'darkgoldenrod' ax1.plot(r.date, rsi, color=fillcolor) ax1.axhline(70, color=fillcolor) ax1.axhline(30, color=fillcolor) ax1.fill_between(r.date, rsi, 70, where=(rsi>=70), facecolor=fillcolor, edgecolor=fillcolor) ax1.fill_between(r.date, rsi, 30, where=(rsi<=30), facecolor=fillcolor, edgecolor=fillcolor)

ax1.text(0.6, 0.9, '>70 = overbought', va='top', transform=ax1.transAxes, fontsize=textsize) ax1.text(0.6, 0.1, '<30 = oversold', transform=ax1.transAxes, fontsize=textsize) ax1.set_ylim(0, 100) ax1.set_yticks([30,70]) ax1.text(0.025, 0.95, 'RSI (14)', va='top', transform=ax1.transAxes, fontsize=textsize) ax1.set_title('%s daily'%ticker) ### plot the price and volume data dx = r.adj_close - r.close low = r.low + dx high = r.high + dx deltas = np.zeros_like(prices) deltas[1:] = np.diff(prices) up = deltas>0 ax2.vlines(r.date[up], low[up], high[up], color='black', label='_nolegend_') ax2.vlines(r.date[~up], low[~up], high[~up], color='black', label='_nolegend_') ma20 = moving_average(prices, 20, type='simple') ma200 = moving_average(prices, 200, type='simple') linema20, = ax2.plot(r.date, ma20, color='blue', lw=2, label='MA (20)') linema200, = ax2.plot(r.date, ma200, color='red', lw=2, label='MA (200)') last = r[-1] s = '%s O:%1.2f H:%1.2f L:%1.2f C:%1.2f, V:%1.1fM Chg:%+1.2f' % ( today.strftime('%d-%b-%Y'), last.open, last.high, last.low, last.close, last.volume*1e-6, last.close-last.open ) t4 = ax2.text(0.3, 0.9, s, transform=ax2.transAxes, fontsize=textsize) props = font_manager.FontProperties(size=10) leg = ax2.legend(loc='center left', shadow=True, fancybox=True, prop=props) leg.get_frame().set_alpha(0.5) volume = (r.close*r.volume)/1e6 # dollar volume in millions vmax = volume.max() poly = ax2t.fill_between(r.date, volume, 0, label='Volume', facecolor=fillcolor, edgecolor=fillcolor) ax2t.set_ylim(0, 5*vmax) ax2t.set_yticks([]) ### compute the MACD indicator fillcolor = 'darkslategrey' nslow = 26 nfast = 12 nema = 9 emaslow, emafast, macd = moving_average_convergence(prices, nslow=nslow, nfast=nfast)

ema9 = moving_average(macd, nema, type='exponential') ax3.plot(r.date, macd, color='black', lw=2) ax3.plot(r.date, ema9, color='blue', lw=1) ax3.fill_between(r.date, macd-ema9, 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor) ax3.text(0.025, 0.95, 'MACD (%d, %d, %d)'%(nfast, nslow, nema), va='top', transform=ax3.transAxes, fontsize=textsize) #ax3.set_yticks([]) # turn off upper axis tick labels, rotate the lower ones, etc for ax in ax1, ax2, ax2t, ax3: if ax!=ax3: for label in ax.get_xticklabels(): label.set_visible(False) else: for label in ax.get_xticklabels(): label.set_rotation(30) label.set_horizontalalignment('right') ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')

class MyLocator(mticker.MaxNLocator): def __init__(self, *args, **kwargs): mticker.MaxNLocator.__init__(self, *args, **kwargs) def __call__(self, *args, **kwargs): return mticker.MaxNLocator.__call__(self, *args, **kwargs) # at most 5 ticks, pruning the upper and lower so they don't overlap # with other ticks #ax2.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both')) #ax3.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both')) ax2.yaxis.set_major_locator(MyLocator(5, prune='both')) ax3.yaxis.set_major_locator(MyLocator(5, prune='both')) plt.show()

""" hexbin is an axes method or pyplot function that is essentially a pcolor of a 2-D histogram with hexagonal cells. It can be much more informative than a scatter plot; in the first subplot below, try substituting 'scatter' for 'hexbin'. """ import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt n = 100000 x = np.random.standard_normal(n)

y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n) xmin = x.min() xmax = x.max() ymin = y.min() ymax = y.max() plt.subplots_adjust(hspace=0.5) plt.subplot(121) plt.hexbin(x,y, cmap=cm.jet) plt.axis([xmin, xmax, ymin, ymax]) plt.title("Hexagon binning") cb = plt.colorbar() cb.set_label('counts') plt.subplot(122) plt.hexbin(x,y,bins='log', cmap=cm.jet) plt.axis([xmin, xmax, ymin, ymax]) plt.title("With a log color scale") cb = plt.colorbar() cb.set_label('log10(N)') plt.show()

""" hexbin is an axes method or pyplot function that is essentially a pcolor of a 2-D histogram with hexagonal cells. """ import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab delta = 0.025 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = Z2-Z1 # difference of Gaussians x = X.ravel() y = Y.ravel() z = Z.ravel() if 1: # make some points 20 times more common than others, but same mean xcond = (-1 < x) & (x < 1) ycond = (-2 < y) & (y < 0) cond = xcond & ycond xnew = x[cond] ynew = y[cond] znew = z[cond] for i in range(20): x = np.hstack((x,xnew)) y = np.hstack((y,ynew)) z = np.hstack((z,znew))

xmin xmax ymin ymax

= = = =

x.min() x.max() y.min() y.max()

gridsize=30 plt.subplot(211) plt.hexbin(x,y, C=z, gridsize=gridsize, marginals=True) plt.axis([xmin, xmax, ymin, ymax]) cb = plt.colorbar() cb.set_label('mean value') plt.subplot(212) plt.hexbin(x,y, gridsize=gridsize) plt.axis([xmin, xmax, ymin, ymax]) cb = plt.colorbar() cb.set_label('N observations') plt.show()

#!/usr/bin/env python from pylab import * import matplotlib.cbook as cbook w, h = 512, 512 datafile = cbook.get_sample_data('ct.raw', asfileobj=False) print 'loading', datafile s = file(datafile, 'rb').read() A = fromstring(s, uint16).astype(float) A *= 1.0/max(A) A.shape = w, h extent = (0, 25, 0, 25) im = imshow(A, cmap=cm.hot, origin='upper', extent=extent) markers = [(15.9, 14.5), (16.8, 15)] x,y = zip(*markers) plot(x, y, 'o') #axis([0,25,0,25])

#axis('off') title('CT density') if 0: x = asum(A,0) subplot(212) bar(arange(w), x) xlim(0,h-1) ylabel('density')

setp(gca(), 'xticklabels', []) show()

#!/usr/bin/env python import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt delta = 0.025 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = Z2-Z1 # difference of Gaussians im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray, origin='lower', extent=[-3,3,-3,3]) plt.show()

#!/usr/bin/env python """ The same (small) array, interpolated with three different interpolation methods. The center of the pixel at A[i,j] is plotted at i+0.5, i+0.5. If you are using interpolation='nearest', the region bounded by (i,j) and (i+1,j+1) will have the same color. If you are using interpolation, the pixel center will have the same color as it does with nearest, but other pixels will be interpolated between the neighboring pixels. Earlier versions of matplotlib (<0.63) tried to hide the edge effects from you by setting the view limits so that they would not be visible. A recent bugfix in antigrain, and a new implementation in the matplotlib._image module which takes advantage of this fix, no longer makes this necessary. To prevent edge effects, when doing interpolation, the matplotlib._image module now pads the input array with identical pixels around the edge. Eg, if you have a 5x5 array with colors a-y as below a f k p u b g l q v c h m r w d i n s x e j o t y

the _image module creates the padded array, a a b c d e e a a b c d e e f f g h i j j

k p o o

k p u u

l q v v

m r w w

n s x x

o t y y

o t y y

does the interpolation/resizing, and then extracts the central region. This allows you to plot the full range of your array w/o edge effects, and for example to layer multiple images of different sizes over one another with different interpolation methods - see examples/layer_images.py. It also implies a performance hit, as this new temporary, padded array must be created. Sophisticated interpolation also implies a performance hit, so if you need maximal performance or have very large images, interpolation='nearest' is suggested. """ from pylab import * A = rand(5,5) figure(1) imshow(A, interpolation='nearest') grid(True) figure(2) imshow(A, interpolation='bilinear') grid(True) figure(3) imshow(A, interpolation='bicubic') grid(True) show()

#!/usr/bin/env python '''imshow with masked array input and out-of-range colors. The second subplot illustrates the use of BoundaryNorm to get a filled contour effect. ''' from pylab import * from numpy import ma import matplotlib.colors as colors delta = 0.025 x = y = arange(-3.0, 3.0, delta) X, Y = meshgrid(x, y) Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10 * (Z2-Z1) # difference of Gaussians # Set up a colormap: palette = cm.gray palette.set_over('r', 1.0) palette.set_under('g', 1.0) palette.set_bad('b', 1.0)

# Alternatively, we could use # palette.set_bad(alpha = 0.0) # to make the bad region transparent. This is the default. # If you comment out all the palette.set* lines, you will see # all the defaults; under and over will be colored with the # first and last colors in the palette, respectively. Zm = ma.masked_where(Z > 1.2, Z) # By setting vmin and vmax in the norm, we establish the # range to which the regular palette color scale is applied. # Anything above that range is colored based on palette.set_over, etc. subplot(1,2,1) im = imshow(Zm, interpolation='bilinear', cmap=palette, norm = colors.Normalize(vmin = -1.0, vmax = 1.0, clip = False), origin='lower', extent=[-3,3,-3,3]) title('Green=low, Red=high, Blue=bad') colorbar(im, extend='both', orientation='horizontal', shrink=0.8) subplot(1,2,2) im = imshow(Zm, interpolation='nearest', cmap=palette, norm = colors.BoundaryNorm([-1, -0.5, -0.2, 0, 0.2, 0.5, 1], ncolors=256, clip = False), origin='lower', extent=[-3,3,-3,3]) title('With BoundaryNorm') colorbar(im, extend='both', spacing='proportional', orientation='horizontal', shrink=0.8) show()

''' This illustrates the NonUniformImage class, which still needs an axes method interface; either a separate interface, or a generalization of imshow. ''' from matplotlib.pyplot import figure, show import numpy as np from matplotlib.image import NonUniformImage interp='nearest' x = np.linspace(-4, 4, 9) x2 = x**3 y = np.linspace(-4, 4, 9) #print 'Size %d points' % (len(x) * len(y)) z = np.sqrt(x[np.newaxis,:]**2 + y[:,np.newaxis]**2) fig = figure() fig.suptitle('NonUniformImage class') ax = fig.add_subplot(221) im = NonUniformImage(ax, interpolation=interp, extent=(-4,4,-4,4)) im.set_data(x, y, z)

ax.images.append(im) ax.set_xlim(-4,4) ax.set_ylim(-4,4) ax.set_title(interp) ax = fig.add_subplot(222) im = NonUniformImage(ax, interpolation=interp, extent=(-64,64,-4,4)) im.set_data(x2, y, z) ax.images.append(im) ax.set_xlim(-64,64) ax.set_ylim(-4,4) ax.set_title(interp) interp = 'bilinear' ax = fig.add_subplot(223) im = NonUniformImage(ax, interpolation=interp, extent=(-4,4,-4,4)) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim(-4,4) ax.set_ylim(-4,4) ax.set_title(interp) ax = fig.add_subplot(224) im = NonUniformImage(ax, interpolation=interp, extent=(-64,64,-4,4)) im.set_data(x2, y, z) ax.images.append(im) ax.set_xlim(-64,64) ax.set_ylim(-4,4) ax.set_title(interp) show()

#!/usr/bin/env python """ You can specify whether images should be plotted with the array origin x[0,0] in the upper left or upper right by using the origin parameter. You can also control the default be setting image.origin in your matplotlibrc file; see http://matplotlib.sourceforge.net/matplotlibrc """ from pylab import * x = arange(100.0); x.shape = 10,10 interp = 'bilinear'; #interp = 'nearest'; lim = -2,11,-2,6 subplot(211, axisbg='g') title('blue should be up') imshow(x, origin='upper', interpolation=interp) #axis(lim) subplot(212, axisbg='y') title('blue should be down') imshow(x, origin='lower', interpolation=interp)

#axis(lim) show()

import numpy from matplotlib.pyplot import figure, show

class IndexTracker: def __init__(self, ax, X): self.ax = ax ax.set_title('use scroll wheel to navigate images') self.X = X rows,cols,self.slices = X.shape self.ind = self.slices/2 self.im = ax.imshow(self.X[:,:,self.ind]) self.update() def onscroll(self, event): print event.button, event.step if event.button=='up': self.ind = numpy.clip(self.ind+1, 0, self.slices-1) else: self.ind = numpy.clip(self.ind-1, 0, self.slices-1) self.update() def update(self): self.im.set_data(self.X[:,:,self.ind]) ax.set_ylabel('slice %s'%self.ind) self.im.axes.figure.canvas.draw() fig = figure() ax = fig.add_subplot(111) X = numpy.random.rand(20,20,40) tracker = IndexTracker(ax, X)

fig.canvas.mpl_connect('scroll_event', tracker.onscroll) show()

#!/usr/bin/env python # implement the example graphs/integral from pyx from pylab import * from matplotlib.patches import Polygon

def func(x): return (x-3)*(x-5)*(x-7)+85 ax = subplot(111) a, b = 2, 9 # integral area x = arange(0, 10, 0.01) y = func(x) plot(x, y, linewidth=1) # make the shaded region ix = arange(a, b, 0.01) iy = func(ix) verts = [(a,0)] + zip(ix,iy) + [(b,0)] poly = Polygon(verts, facecolor='0.8', edgecolor='k') ax.add_patch(poly) text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment='center', fontsize=20) axis([0,10, 0, 180]) figtext(0.9, 0.05, 'x') figtext(0.1, 0.9, 'y') ax.set_xticks((a,b)) ax.set_xticklabels(('a','b')) ax.set_yticks([]) show()

#!/usr/bin/env python """ Layer images above one another using alpha blending """ from __future__ import division from pylab import * def func3(x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) # make these smaller to increase the resolution dx, dy = 0.05, 0.05 x = arange(-3.0, 3.0, dx) y = arange(-3.0, 3.0, dy) X,Y = meshgrid(x, y) # # # # # # when layering multiple images, the images need to have the same extent. This does not mean they need to have the same shape, but they both need to render to the same coordinate system determined by xmin, xmax, ymin, ymax. Note if you use different interpolations for the images their apparent extent could be different due to interpolation edge effects

xmin, xmax, ymin, ymax = amin(x), amax(x), amin(y), amax(y) extent = xmin, xmax, ymin, ymax fig = plt.figure(frameon=False) Z1 = array(([0,1]*4 + [1,0]*4)*4); Z1.shape = 8,8 # chessboard im1 = imshow(Z1, cmap=cm.gray, interpolation='nearest', extent=extent) hold(True) Z2 = func3(X, Y) im2 = imshow(Z2, cmap=cm.jet, alpha=.9, interpolation='bilinear', extent=extent) #axis([xmin, xmax, ymin, ymax]) show()

""" This file was written to test matplotlib's autolegend placement algorithm, but shows lots of different ways to create legends so is useful as a general examples Thanks to John Gill and Phil ?? for help at the matplotlib sprint at pycon 2005 where the auto-legend support was written. """ from pylab import * import sys rcParams['legend.loc'] = 'best' N = 100 x = arange(N) def fig_1(): figure(1) t = arange(0, 40.0 * pi, 0.1) l, = plot(t, 100*sin(t), 'r', label='sine') legend() def fig_2(): figure(2) plot(x, 'o', label='x=y') legend() def fig_3(): figure(3) plot(x, -x, 'o', label='x= -y') legend() def fig_4(): figure(4) plot(x, ones(len(x)), 'o', label='y=1') plot(x, -ones(len(x)), 'o', label='y=-1') legend()

def fig_5(): figure(5) n, bins, patches = hist(randn(1000), 40, normed=1) l, = plot(bins, normpdf(bins, 0.0, 1.0), 'r--', label='fit', linewidth=3) legend([l, patches[0]], ['fit', 'hist']) def fig_6(): figure(6) plot(x, 50-x, 'o', label='y=1') plot(x, x-50, 'o', label='y=-1') legend() def fig_7(): figure(7) xx = x - (N/2.0) plot(xx, (xx*xx)-1225, 'bo', label='$y=x^2$') plot(xx, 25*xx, 'go', label='$y=25x$') plot(xx, -25*xx, 'mo', label='$y=-25x$') legend() def fig_8(): figure(8) b1 = bar(x, x, color='m') b2 = bar(x, x[::-1], color='g') legend([b1[0], b2[0]], ['up', 'down']) def fig_9(): figure(9) b1 = bar(x, -x) b2 = bar(x, -x[::-1], color='r') legend([b1[0], b2[0]], ['down', 'up']) def fig_10(): figure(10) b1 = bar(x, x, bottom=-100, color='m') b2 = bar(x, x[::-1], bottom=-100, color='g') b3 = bar(x, -x, bottom=100) b4 = bar(x, -x[::-1], bottom=100, color='r') legend([b1[0], b2[0], b3[0], b4[0]], ['bottom right', 'bottom left', 'top left', 'top right']) if __name__ == '__main__': nfigs = 10 figures = [] for f in sys.argv[1:]: try: figures.append(int(f)) except ValueError: pass if len(figures) == 0: figures = range(1, nfigs+1) for fig in figures: fn_name = "fig_%d" % fig fn = globals()[fn_name] fn()

show()

#!/usr/bin/env python # # Make a legend for specific lines. from pylab import * t1 = arange(0.0, 2.0, 0.1) t2 = arange(0.0, 2.0, 0.01) # note that plot returns a list of lines. The "l1, = plot" usage # extracts the first element of the list inot l1 using tuple # unpacking. So l1 is a Line2D instance, not a sequence of lines l1, = plot(t2, exp(-t2)) l2, l3 = plot(t2, sin(2*pi*t2), '--go', t1, log(1+t1), '.') l4, = plot(t2, exp(-t2)*sin(2*pi*t2), 'rs-.') legend( (l2, l4), ('oscillatory', 'damped'), 'upper right', shadow=True) xlabel('time') ylabel('volts') title('Damped oscillation') #axis([0,2,-1,1]) show()

#!/usr/bin/env python from pylab import * N=1000 props = dict( alpha=0.5, edgecolors='none' ) handles = [] colours = ['red', 'green', 'blue', 'magenta', 'cyan', 'yellow'] colours = ['red', 'green', 'blue'] for colour in colours: x, y = rand(2,N) s = 400.0 * rand(N) handles.append(scatter(x, y, c=colour, s=s, **props)) legend(handles, colours) grid(True) show()

#!/usr/bin/env python # This should probably be replaced with a demo that shows all # line and marker types in a single panel, with labels. import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np t = np.arange(0.0, 1.0, 0.1)

s = np.sin(2*np.pi*t) linestyles = ['_', '-', '--', ':'] markers = [] for m in Line2D.markers: try: if len(m) == 1 and m != ' ': markers.append(m) except TypeError: pass styles = markers + [ r'$\lambda$', r'$\bowtie$', r'$\circlearrowleft$', r'$\clubsuit$', r'$\checkmark$'] colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k') plt.figure(figsize=(8,8)) axisNum = 0 for row in range(6): for col in range(5): axisNum += 1 ax = plt.subplot(6, 5, axisNum) color = colors[axisNum % len(colors)] if axisNum < len(linestyles): plt.plot(t, s, linestyles[axisNum], color=color, markersize=10) else: style = styles[(axisNum - len(linestyles)) % len(styles)] plt.plot(t, s, linestyle='None', marker=style, color=color, markersize=10) ax.set_yticklabels([]) ax.set_xticklabels([]) plt.show()

import numpy as np import matplotlib.pyplot as plt plt.subplots_adjust(hspace=0.4) t = np.arange(0.01, 20.0, 0.01) # log y axis plt.subplot(221) plt.semilogy(t, np.exp(-t/5.0)) plt.title('semilogy') plt.grid(True) # log x axis plt.subplot(222) plt.semilogx(t, np.sin(2*np.pi*t)) plt.title('semilogx') plt.grid(True)

# log x and y axis plt.subplot(223) plt.loglog(t, 20*np.exp(-t/10.0), basex=2) plt.grid(True) plt.title('loglog base 4 on x') # with errorbars: clip non-positive values ax = plt.subplot(224) ax.set_xscale("log", nonposx='clip') ax.set_yscale("log", nonposy='clip') x = 10.0**np.linspace(0.0, 2.0, 20) y = x**2.0 plt.errorbar(x, y, xerr=0.1*x, yerr=5.0+0.75*y) ax.set_ylim(ymin=0.1) ax.set_title('Errorbars go negative') plt.show()

""" The techniques here are no longer required with the new support for spines in matplotlib -- see http://matplotlib.sourceforge.net/examples/pylab_examples/spine_placement_dem o.html. This example should be considered deprecated and is left just for demo purposes for folks wanting to make a pseudo-axis """ import numpy as np from pylab import figure, show import matplotlib.lines as lines def make_xaxis(ax, yloc, offset=0.05, **props): xmin, xmax = ax.get_xlim() locs = [loc for loc in ax.xaxis.get_majorticklocs() if loc>=xmin and loc<=xmax] tickline, = ax.plot(locs, [yloc]*len(locs),linestyle='', marker=lines.TICKDOWN, **props) axline, = ax.plot([xmin, xmax], [yloc, yloc], **props) tickline.set_clip_on(False) axline.set_clip_on(False) for loc in locs: ax.text(loc, yloc-offset, '%1.1f'%loc, horizontalalignment='center', verticalalignment='top') def make_yaxis(ax, xloc=0, offset=0.05, **props): ymin, ymax = ax.get_ylim() locs = [loc for loc in ax.yaxis.get_majorticklocs() if loc>=ymin and loc<=ymax] tickline, = ax.plot([xloc]*len(locs), locs, linestyle='',

marker=lines.TICKLEFT, **props) axline, = ax.plot([xloc, xloc], [ymin, ymax], **props) tickline.set_clip_on(False) axline.set_clip_on(False) for loc in locs: ax.text(xloc-offset, loc, '%1.1f'%loc, verticalalignment='center', horizontalalignment='right') props = dict(color='black', linewidth=2, markeredgewidth=2) x = np.arange(200.) y = np.sin(2*np.pi*x/200.) + np.random.rand(200)-0.5 fig = figure(facecolor='white') ax = fig.add_subplot(111, frame_on=False) ax.axison = False ax.plot(x, y, 'd', markersize=8, markerfacecolor='blue') ax.set_xlim(0, 200) ax.set_ylim(-1.5, 1.5) make_xaxis(ax, 0, offset=0.1, **props) make_yaxis(ax, 0, offset=5, **props) show()

#!/usr/bin/env python """Simple matshow() example.""" from matplotlib.pylab import * def samplemat(dims): """Make a matrix with all zeros and increasing elements on the diagonal""" aa = zeros(dims) for i in range(min(dims)): aa[i,i] = i return aa # Make a few matrices of strange sizes dimlist = [(12,12),(128,64),(64,512),(1024,128)] for d in dimlist: matshow(samplemat(d)) # Display a random matrix with a specified figure number and a grayscale colormap matshow(rand(64,64),fignum=100,cmap=cm.gray) show()

#!/usr/bin/env python ''' Make a set of images with a single colormap, norm, and colorbar.

It also illustrates colorbar tick labelling with a multiplier. ''' from from from from from matplotlib.pyplot import figure, show, axes, sci matplotlib import cm, colors matplotlib.font_manager import FontProperties numpy import amin, amax, ravel numpy.random import rand

Nr = 3 Nc = 2 fig = figure() cmap = cm.cool figtitle = 'Multiple images' t = fig.text(0.5, 0.95, figtitle, horizontalalignment='center', fontproperties=FontProperties(size=16)) cax = fig.add_axes([0.2, 0.08, 0.6, 0.04]) w = 0.4 h = 0.22 ax = [] images = [] vmin = 1e40 vmax = -1e40 for i in range(Nr): for j in range(Nc): pos = [0.075 + j*1.1*w, 0.18 + i*1.2*h, w, h] a = fig.add_axes(pos) if i > 0: a.set_xticklabels([]) # Make some fake data with a range that varies # somewhat from one plot to the next. data =((1+i+j)/10.0)*rand(10,20)*1e-6 dd = ravel(data) # Manually find the min and max of all colors for # use in setting the color scale. vmin = min(vmin, amin(dd)) vmax = max(vmax, amax(dd)) images.append(a.imshow(data, cmap=cmap)) ax.append(a) # Set the first image as the master, with all the others # observing it for changes in cmap or norm. class ImageFollower: 'update image in response to changes in clim or cmap on another image' def __init__(self, follower): self.follower = follower def __call__(self, leader): self.follower.set_cmap(leader.get_cmap()) self.follower.set_clim(leader.get_clim())

norm = colors.Normalize(vmin=vmin, vmax=vmax) for i, im in enumerate(images): im.set_norm(norm) if i > 0: images[0].callbacksSM.connect('changed', ImageFollower(im)) # The colorbar is also based on this master image. fig.colorbar(images[0], cax, orientation='horizontal') # We need the following only if we want to run this interactively and # modify the colormap: axes(ax[0]) sci(images[0]) show() # Return the current axes to the first one, # because the current image must be in current axes.

#!/usr/bin/env python """ See pcolor_demo2 for a much faster way of generating pcolor plots """ from __future__ import division from pylab import * def func3(x,y): return (1- x/2 + x**5 + y**3)*exp(-x**2-y**2) # make these smaller to increase the resolution dx, dy = 0.05, 0.05 x = arange(-3.0, 3.0, dx) y = arange(-3.0, 3.0, dy) X,Y = meshgrid(x, y) Z = func3(X, Y) ax = subplot(111) im = imshow(Z, cmap=cm.jet) #im.set_interpolation('nearest') #im.set_interpolation('bicubic') im.set_interpolation('bilinear') #ax.set_image_extent(-3, 3, -3, 3) show()

from pylab import * from matplotlib.colors import LogNorm N = 100 x = linspace(-3.0, 3.0, N)

y = linspace(-2.0, 2.0, N) X, Y = meshgrid(x, y) # A low hump with a spike coming out of the top right. # Needs to have z/colour axis on a log scale so we see both hump and spike. # linear scale only shows the spike. Z1 = bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) + 0.1*bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) subplot(2,1,1) pcolor(X, Y, Z1, norm=LogNorm(vmin=Z1.min(), vmax=Z1.max())) colorbar() subplot(2,1,2) pcolor(X, Y, Z1) colorbar() show()

from pylab import plotfile, show, gca import matplotlib.cbook as cbook fname = cbook.get_sample_data('msft.csv', asfileobj=False) fname2 = cbook.get_sample_data('data_x_x2_x3.csv', asfileobj=False) # test 1; use ints plotfile(fname, (0,5,6)) # test 2; use names plotfile(fname, ('date', 'volume', 'adj_close')) # test 3; use semilogy for volume plotfile(fname, ('date', 'volume', 'adj_close'), plotfuncs={'volume': 'semilogy'}) # test 4; use semilogy for volume plotfile(fname, (0,5,6), plotfuncs={5:'semilogy'}) #test 5; single subplot plotfile(fname, ('date', 'open', 'high', 'low', 'close'), subplots=False) # test 6; labeling, if no names in csv-file plotfile(fname2, cols=(0,1,2), delimiter=' ', names=['$x$', '$f(x)=x^2$', '$f(x)=x^3$']) # test 7; more than one file per figure--illustrated here with a single file plotfile(fname2, cols=(0, 1), delimiter=' ') plotfile(fname2, cols=(0, 2), newfig=False, delimiter=' ') # use current figure gca().set_xlabel(r'$x$') gca().set_ylabel(r'$f(x) = x^2, x^3$') # test 8; use bar for volume

plotfile(fname, (0,5,6), plotfuncs={5:'bar'}) show()

#!/usr/bin/env python import numpy as np import matplotlib.cm as cm from matplotlib.pyplot import figure, show, rc # force square figure and square axes looks better for polar, IMO fig = figure(figsize=(8,8)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) N = 20 theta = np.arange(0.0, 2*np.pi, 2*np.pi/N) radii = 10*np.random.rand(N) width = np.pi/4*np.random.rand(N) bars = ax.bar(theta, radii, width=width, bottom=0.0) for r,bar in zip(radii, bars): bar.set_facecolor( cm.jet(r/10.)) bar.set_alpha(0.5) show()

#!/usr/bin/env python # # matplotlib now has a PolarAxes class and a polar function in the # matplotlib interface. This is considered alpha and the interface # may change as we work out how polar axes should best be integrated # # The only function that has been tested on polar axes is "plot" (the # pylab interface function "polar" calls ax.plot where ax is a # PolarAxes) -- other axes plotting functions may work on PolarAxes # but haven't been tested and may need tweaking. # # you can get get a PolarSubplot instance by doing, for example # # subplot(211, polar=True) # # or a PolarAxes instance by doing # axes([left, bottom, width, height], polar=True) # # The view limits (eg xlim and ylim) apply to the lower left and upper # right of the rectangular box that surrounds to polar axes. Eg if # you have # # r = arange(0,1,0.01) # theta = 2*pi*r # # the lower left corner is 5/4pi, sqrt(2) and the # upper right corner is 1/4pi, sqrt(2) #

# you could change the radial bounding box (zoom out) by setting the # ylim (radial coordinate is the second argument to the plot command, # as in MATLAB, though this is not advised currently because it is not # clear to me how the axes should behave in the change of view limits. # Please advise me if you have opinions. Likewise, the pan/zoom # controls probably do not do what you think they do and are better # left alone on polar axes. Perhaps I will disable them for polar # axes unless we come up with a meaningful, useful and functional # implementation for them. # # See the pylab rgrids and thetagrids functions for # information on how to customize the grid locations and labels import matplotlib import numpy as np from matplotlib.pyplot import figure, show, rc, grid # radar green, solid grid lines rc('grid', color='#316931', linewidth=1, linestyle='-') rc('xtick', labelsize=15) rc('ytick', labelsize=15) # force square figure and square axes looks better for polar, IMO width, height = matplotlib.rcParams['figure.figsize'] size = min(width, height) # make a square figure fig = figure(figsize=(size, size)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c') r = np.arange(0, 3.0, 0.01) theta = 2*np.pi*r ax.plot(theta, r, color='#ee8d18', lw=3) ax.set_rmax(2.0) grid(True) ax.set_title("And there was much rejoicing!", fontsize=20) show()

#This example shows the effects of some of the different PSD parameters import numpy as np import matplotlib.pyplot as plt dt = np.pi / 100. fs = 1. / dt t = np.arange(0, 8, dt) y = 10. * np.sin(2 * np.pi * 4 * t) + 5. * np.sin(2 * np.pi * 4.25 * t) y = y + np.random.randn(*t.shape) #Plot the raw time series fig = plt.figure() fig.subplots_adjust(hspace=0.45, wspace=0.3) ax = fig.add_subplot(2, 1, 1) ax.plot(t, y) #Plot the PSD with different amounts of zero padding. This uses the entire #time series at once

ax2 = fig.add_subplot(2, 3, 4) ax2.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs) ax2.psd(y, NFFT=len(t), pad_to=len(t)*2, Fs=fs) ax2.psd(y, NFFT=len(t), pad_to=len(t)*4, Fs=fs) plt.title('zero padding') #Plot the PSD with different block sizes, Zero pad to the length of the orignal #data sequence. ax3 = fig.add_subplot(2, 3, 5, sharex=ax2, sharey=ax2) ax3.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs) ax3.psd(y, NFFT=len(t)//2, pad_to=len(t), Fs=fs) ax3.psd(y, NFFT=len(t)//4, pad_to=len(t), Fs=fs) ax3.set_ylabel('') plt.title('block size') #Plot the PSD with different amounts of overlap between blocks ax4 = fig.add_subplot(2, 3, 6, sharex=ax2, sharey=ax2) ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=0, Fs=fs) ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.05*len(t)/2.), Fs=fs) ax4.psd(y, NFFT=len(t)//2, pad_to=len(t), noverlap=int(0.2*len(t)/2.), Fs=fs) ax4.set_ylabel('') plt.title('overlap') plt.show()

#!/usr/bin/env python """ pcolormesh uses a QuadMesh, a faster generalization of pcolor, but with some restrictions. This demo illustrates a bug in quadmesh with masked data. """ import numpy as np from matplotlib.pyplot import figure, show, savefig from matplotlib import cm, colors from numpy import ma n = 12 x = np.linspace(-1.5,1.5,n) y = np.linspace(-1.5,1.5,n*2) X,Y = np.meshgrid(x,y); Qx = np.cos(Y) - np.cos(X) Qz = np.sin(Y) + np.sin(X) Qx = (Qx + 1.1) Z = np.sqrt(X**2 + Y**2)/5; Z = (Z - Z.min()) / (Z.max() - Z.min()) # The color array can include masked values: Zm = ma.masked_where(np.fabs(Qz) < 0.5*np.amax(Qz), Z) fig = figure()

ax = fig.add_subplot(121) ax.set_axis_bgcolor("#bdb76b") ax.pcolormesh(Qx,Qz,Z, shading='gouraud') ax.set_title('Without masked values') ax = fig.add_subplot(122) ax.set_axis_bgcolor("#bdb76b") # You can control the color of the masked region: #cmap = cm.jet #cmap.set_bad('r', 1.0) #ax.pcolormesh(Qx,Qz,Zm, cmap=cmap) # Or use the default, which is transparent: col = ax.pcolormesh(Qx,Qz,Zm,shading='gouraud') ax.set_title('With masked values') show()

''' Demonstration of quiver and quiverkey functions. This is using the new version coming from the code in quiver.py. Known problem: the plot autoscaling does not take into account the arrows, so those on the boundaries are often out of the picture. This is *not* an easy problem to solve in a perfectly general way. The workaround is to manually expand the axes. ''' from pylab import * from numpy import ma X,Y = meshgrid( arange(0,2*pi,.2),arange(0,2*pi,.2) ) U = cos(X) V = sin(Y) #1 figure() Q = quiver( U, V) qk = quiverkey(Q, 0.5, 0.92, 2, r'$2 \frac{m}{s}$', labelpos='W', fontproperties={'weight': 'bold'}) l,r,b,t = axis() dx, dy = r-l, t-b axis([l-0.05*dx, r+0.05*dx, b-0.05*dy, t+0.05*dy]) title('Minimal arguments, no kwargs') #2 figure() Q = quiver( X, Y, U, V, units='width') qk = quiverkey(Q, 0.9, 0.95, 2, r'$2 \frac{m}{s}$', labelpos='E', coordinates='figure', fontproperties={'weight': 'bold'}) axis([-1, 7, -1, 7]) title('scales with plot width, not view')

#3 figure() Q = quiver( X[::3, ::3], Y[::3, ::3], U[::3, ::3], V[::3, ::3], pivot='mid', color='r', units='inches' ) qk = quiverkey(Q, 0.5, 0.03, 1, r'$1 \frac{m}{s}$', fontproperties={'weight': 'bold'}) plot( X[::3, ::3], Y[::3, ::3], 'k.') axis([-1, 7, -1, 7]) title("pivot='mid'; every third arrow; units='inches'") #4 figure() M = sqrt(pow(U, 2) + pow(V, 2)) Q = quiver( X, Y, U, V, M, units='x', pivot='tip', width=0.022, scale=1/0.15) qk = quiverkey(Q, 0.9, 1.05, 1, r'$1 \frac{m}{s}$', labelpos='E', fontproperties={'weight': 'bold'}) plot(X, Y, 'k.') axis([-1, 7, -1, 7]) title("scales with x view; pivot='tip'") #5 figure() Q = quiver( X[::3, ::3], Y[::3, ::3], U[::3, ::3], V[::3, ::3], color='r', units='x', linewidths=(2,), edgecolors=('k'), headaxislength=5 ) qk = quiverkey(Q, 0.5, 0.03, 1, r'$1 \frac{m}{s}$', fontproperties={'weight': 'bold'}) axis([-1, 7, -1, 7]) title("triangular head; scale with x view; black edges") #6 figure() M = zeros(U.shape, dtype='bool') M[U.shape[0]/3:2*U.shape[0]/3,U.shape[1]/3:2*U.shape[1]/3] = True U = ma.masked_array(U, mask=M) V = ma.masked_array(V, mask=M) Q = quiver( U, V) qk = quiverkey(Q, 0.5, 0.92, 2, r'$2 \frac{m}{s}$', labelpos='W', fontproperties={'weight': 'bold'}) l,r,b,t = axis() dx, dy = r-l, t-b axis([l-0.05*dx, r+0.05*dx, b-0.05*dy, t+0.05*dy]) title('Minimal arguments, no kwargs - masked values') show()

import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LightSource # example showing how to make shaded relief plots # like mathematica

# (http://reference.wolfram.com/mathematica/ref/ReliefPlot.html) # or Generic Mapping Tools # (http://gmt.soest.hawaii.edu/gmt/doc/gmt/html/GMT_Docs/node145.html) # test data X,Y=np.mgrid[-5:5:0.05,-5:5:0.05] Z=np.sqrt(X**2+Y**2)+np.sin(X**2+Y**2) # create light source object. ls = LightSource(azdeg=0,altdeg=65) # shade data, creating an rgb array. rgb = ls.shade(Z,plt.cm.copper) # plot un-shaded and shaded images. plt.figure(figsize=(12,5)) plt.subplot(121) plt.imshow(Z,cmap=plt.cm.copper) plt.title('imshow') plt.xticks([]); plt.yticks([]) plt.subplot(122) plt.imshow(rgb) plt.title('imshow with shading') plt.xticks([]); plt.yticks([]) plt.show()

""" Comparison of griddata and tricontour for an unstructured triangular grid. """ import matplotlib.pyplot as plt import matplotlib.tri as tri import numpy as np from numpy.random import uniform, seed from matplotlib.mlab import griddata import time seed(0) npts = 200 ngridx = 100 ngridy = 200 x = uniform(-2,2,npts) y = uniform(-2,2,npts) z = x*np.exp(-x**2-y**2) # griddata and contour. start = time.clock() plt.subplot(211) xi = np.linspace(-2.1,2.1,ngridx) yi = np.linspace(-2.1,2.1,ngridy) zi = griddata(x,y,z,xi,yi,interp='linear') plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k') plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet) plt.colorbar() # draw colorbar plt.plot(x, y, 'ko', ms=3) plt.xlim(-2,2) plt.ylim(-2,2) plt.title('griddata and contour (%d points, %d grid points)' % (npts, ngridx*ngridy))

print 'griddata and contour seconds:', time.clock() - start # tricontour. start = time.clock() plt.subplot(212) triang = tri.Triangulation(x, y) plt.tricontour(x, y, z, 15, linewidths=0.5, colors='k') plt.tricontourf(x, y, z, 15, cmap=plt.cm.jet) plt.colorbar() plt.plot(x, y, 'ko', ms=3) plt.xlim(-2,2) plt.ylim(-2,2) plt.title('tricontour (%d points)' % npts) print 'tricontour seconds:', time.clock() - start plt.show()

from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X, Y, Z = axes3d.get_test_data(0.05) cset = ax.contour(X, Y, Z) ax.clabel(cset, fontsize=9, inline=1) plt.show()

from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca(projection='3d') X, Y, Z = axes3d.get_test_data(0.05) cset = ax.contour(X, Y, Z, extend3d=True) ax.clabel(cset, fontsize=9, inline=1) plt.show()

import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspace(-2, 2, 100) r = z**2 + 1 x = r * np.sin(theta) y = r * np.cos(theta)

ax.plot(x, y, z, label='parametric curve') ax.legend() plt.show()

# Plot of the Lorenz Attractor based on Edward Lorenz's 1963 "Deterministic # Nonperiodic Flow" publication. # http://journals.ametsoc.org/doi/abs/10.1175/15200469%281963%29020%3C0130%3ADNF%3E2.0.CO%3B2 # # Note: Because this is a simple non-linear ODE, it would be more easily # done using SciPy's ode solver, but this approach depends only # upon NumPy. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def lorenz(x, y, z, s=10, r=28, b=2.667) : x_dot = s*(y - x) y_dot = r*x - y - x*z z_dot = x*y - b*z return x_dot, y_dot, z_dot dt = 0.01 stepCnt = 10000 # Need one more for the initial values xs = np.empty((stepCnt + 1,)) ys = np.empty((stepCnt + 1,)) zs = np.empty((stepCnt + 1,)) # Setting initial values xs[0], ys[0], zs[0] = (0., 1., 1.05) # Stepping through "time". for i in xrange(stepCnt) : # Derivatives of the X, Y, Z state x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i]) xs[i + 1] = xs[i] + (x_dot * dt) ys[i + 1] = ys[i] + (y_dot * dt) zs[i + 1] = zs[i] + (z_dot * dt) fig = plt.figure() ax = fig.gca(projection='3d') ax.plot(xs, ys, zs) ax.set_xlabel("X Axis") ax.set_ylabel("Y Axis") ax.set_zlabel("Z Axis") plt.show()

from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np plt.ion() fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X, Y, Z = axes3d.get_test_data(0.1) ax.plot_wireframe(X, Y, Z, rstride=5, cstride=5) for angle in range(0, 360): ax.view_init(30, angle) plt.draw()

from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b') plt.show()

""" A very simple 'animation' of a 3D plot """ from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np import time def generate(X, Y, phi): R = 1 - np.sqrt(X**2 + Y**2) return np.cos(2 * np.pi * X + phi) * R plt.ion() fig = plt.figure() ax = fig.add_subplot(111, projection='3d') xs = np.linspace(-1, 1, 50) ys = np.linspace(-1, 1, 50) X, Y = np.meshgrid(xs, ys) Z = generate(X, Y, 0.0) wframe = None

tstart = time.time() for phi in np.linspace(0, 360 / 2 / np.pi, 100): oldcol = wframe Z = generate(X, Y, phi) wframe = ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2) # Remove old line collection before drawing if oldcol is not None: ax.collections.remove(oldcol) plt.draw() print 'FPS: %f' % (100 / (time.time() - tstart))

from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0, antialiased=False) ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()

---------------------------------------------------------------------------------------------------------------------------

You might also like