hash
stringlengths
64
64
content
stringlengths
0
1.51M
e7dd3433204fa5da7ceebcbcc327bfae6e10f14f654fb5f72930ecd17a15739d
""" ============== Manual Contour ============== Example of displaying your own contour lines and polygons using ContourSet. """ import matplotlib.pyplot as plt from matplotlib.contour import ContourSet import matplotlib.cm as cm ############################################################################### # Contour lines for each level are a list/tuple of polygons. lines0 = [[[0, 0], [0, 4]]] lines1 = [[[2, 0], [1, 2], [1, 3]]] lines2 = [[[3, 0], [3, 2]], [[3, 3], [3, 4]]] # Note two lines. ############################################################################### # Filled contours between two levels are also a list/tuple of polygons. # Points can be ordered clockwise or anticlockwise. filled01 = [[[0, 0], [0, 4], [1, 3], [1, 2], [2, 0]]] filled12 = [[[2, 0], [3, 0], [3, 2], [1, 3], [1, 2]], # Note two polygons. [[1, 4], [3, 4], [3, 3]]] ############################################################################### plt.figure() # Filled contours using filled=True. cs = ContourSet(plt.gca(), [0, 1, 2], [filled01, filled12], filled=True, cmap=cm.bone) cbar = plt.colorbar(cs) # Contour lines (non-filled). lines = ContourSet(plt.gca(), [0, 1, 2], [lines0, lines1, lines2], cmap=cm.cool, linewidths=3) cbar.add_lines(lines) plt.axis([-0.5, 3.5, -0.5, 4.5]) plt.title('User-specified contours') ############################################################################### # Multiple filled contour lines can be specified in a single list of polygon # vertices along with a list of vertex kinds (code types) as described in the # Path class. This is particularly useful for polygons with holes. # Here a code type of 1 is a MOVETO, and 2 is a LINETO. plt.figure() filled01 = [[[0, 0], [3, 0], [3, 3], [0, 3], [1, 1], [1, 2], [2, 2], [2, 1]]] kinds01 = [[1, 2, 2, 2, 1, 2, 2, 2]] cs = ContourSet(plt.gca(), [0, 1], [filled01], [kinds01], filled=True) cbar = plt.colorbar(cs) plt.axis([-0.5, 3.5, -0.5, 3.5]) plt.title('User specified filled contours with holes') plt.show()
1de2140ade31dc41855afd1cdcfe06ae646207e81278054809dcef2d4a6a15ef
""" ============= Plotfile Demo ============= Example use of ``plotfile`` to plot data directly from a file. """ import matplotlib.pyplot as plt 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 plt.plotfile(fname, (0, 5, 6)) # test 2; use names plt.plotfile(fname, ('date', 'volume', 'adj_close')) # test 3; use semilogy for volume plt.plotfile(fname, ('date', 'volume', 'adj_close'), plotfuncs={'volume': 'semilogy'}) # test 4; use semilogy for volume plt.plotfile(fname, (0, 5, 6), plotfuncs={5: 'semilogy'}) # test 5; single subplot plt.plotfile(fname, ('date', 'open', 'high', 'low', 'close'), subplots=False) # test 6; labeling, if no names in csv-file plt.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 plt.plotfile(fname2, cols=(0, 1), delimiter=' ') plt.plotfile(fname2, cols=(0, 2), newfig=False, delimiter=' ') # use current figure plt.xlabel(r'$x$') plt.ylabel(r'$f(x) = x^2, x^3$') # test 8; use bar for volume plt.plotfile(fname, (0, 5, 6), plotfuncs={5: 'bar'}) plt.show()
9fc04b73b534f57fa72e4f116276d17baad54c7071ac5512961bf56d8fb45b03
""" ============= Coords Report ============= Override the default reporting of coords. """ import matplotlib.pyplot as plt import numpy as np def millions(x): return '$%1.1fM' % (x*1e-6) # Fixing random state for reproducibility np.random.seed(19680801) x = np.random.rand(20) y = 1e7*np.random.rand(20) fig, ax = plt.subplots() ax.fmt_ydata = millions plt.plot(x, y, 'o') plt.show()
2931ccead5592386c427037265e518ef61590490d621f4c91fe33627043dc983
""" ============= Font indexing ============= This example shows how the font tables relate to one another. """ import os import matplotlib from matplotlib.ft2font import ( FT2Font, KERNING_DEFAULT, KERNING_UNFITTED, KERNING_UNSCALED) font = FT2Font( os.path.join(matplotlib.get_data_path(), 'fonts/ttf/DejaVuSans.ttf')) font.set_charmap(0) codes = font.get_charmap().items() # make a charname to charcode and glyphind dictionary coded = {} glyphd = {} for ccode, glyphind in codes: name = font.get_glyph_name(glyphind) coded[name] = ccode glyphd[name] = glyphind # print(glyphind, ccode, hex(int(ccode)), name) code = coded['A'] glyph = font.load_char(code) print(glyph.bbox) print(glyphd['A'], glyphd['V'], coded['A'], coded['V']) print('AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_DEFAULT)) print('AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_UNFITTED)) print('AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_UNSCALED)) print('AV', font.get_kerning(glyphd['A'], glyphd['T'], KERNING_UNSCALED))
e5ece6767e014101f1685a4c912aa80b2b2f849693992879747e011da863e020
""" =================== Agg Buffer To Array =================== Convert a rendered figure to its image (NumPy array) representation. """ import matplotlib.pyplot as plt import numpy as np # make an agg figure fig, ax = plt.subplots() ax.plot([1, 2, 3]) ax.set_title('a simple figure') fig.canvas.draw() # grab the pixel buffer and dump it into a numpy array X = np.array(fig.canvas.renderer.buffer_rgba()) # now display the array X as an Axes in a new figure fig2 = plt.figure() ax2 = fig2.add_subplot(111, frameon=False) ax2.imshow(X) plt.show()
4ed9f4ecce33793f641f29bec844f1197488fcf704374348ec8ed8da441642d1
""" ========== Table Demo ========== Demo of table function to display a table within a plot. """ import numpy as np import matplotlib.pyplot as plt data = [[ 66386, 174296, 75131, 577908, 32015], [ 58230, 381139, 78045, 99308, 160454], [ 89135, 80552, 152558, 497981, 603535], [ 78415, 81858, 150656, 193263, 69638], [139361, 331509, 343164, 781380, 52269]] columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail') rows = ['%d year' % x for x in (100, 50, 20, 10, 5)] values = np.arange(0, 2500, 500) value_increment = 1000 # Get some pastel shades for the colors colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows))) n_rows = len(data) index = np.arange(len(columns)) + 0.3 bar_width = 0.4 # Initialize the vertical-offset for the stacked bar chart. y_offset = np.zeros(len(columns)) # Plot bars and create text labels for the table cell_text = [] for row in range(n_rows): plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row]) y_offset = y_offset + data[row] cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset]) # Reverse colors and text labels to display the last value at the top. colors = colors[::-1] cell_text.reverse() # Add a table at the bottom of the axes the_table = plt.table(cellText=cell_text, rowLabels=rows, rowColours=colors, colLabels=columns, loc='bottom') # Adjust layout to make room for the table: plt.subplots_adjust(left=0.2, bottom=0.2) plt.ylabel("Loss in ${0}'s".format(value_increment)) plt.yticks(values * value_increment, ['%d' % val for val in values]) plt.xticks([]) plt.title('Loss by Disaster') plt.show()
34d6005373c6d2d4b081bb562320e59de4dfaf644713a1dff109ea7c6ec7d691
""" =============== Patheffect Demo =============== """ import matplotlib.pyplot as plt import matplotlib.patheffects as PathEffects import numpy as np plt.figure(figsize=(8, 3)) ax1 = plt.subplot(131) ax1.imshow([[1, 2], [2, 3]]) txt = ax1.annotate("test", (1., 1.), (0., 0), arrowprops=dict(arrowstyle="->", connectionstyle="angle3", lw=2), size=20, ha="center", path_effects=[PathEffects.withStroke(linewidth=3, foreground="w")]) txt.arrow_patch.set_path_effects([ PathEffects.Stroke(linewidth=5, foreground="w"), PathEffects.Normal()]) pe = [PathEffects.withStroke(linewidth=3, foreground="w")] ax1.grid(True, linestyle="-", path_effects=pe) ax2 = plt.subplot(132) arr = np.arange(25).reshape((5, 5)) ax2.imshow(arr) cntr = ax2.contour(arr, colors="k") plt.setp(cntr.collections, path_effects=[ PathEffects.withStroke(linewidth=3, foreground="w")]) clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True) plt.setp(clbls, path_effects=[ PathEffects.withStroke(linewidth=3, foreground="w")]) # shadow as a path effect ax3 = plt.subplot(133) p1, = ax3.plot([0, 1], [0, 1]) leg = ax3.legend([p1], ["Line 1"], fancybox=True, loc='upper left') leg.legendPatch.set_path_effects([PathEffects.withSimplePatchShadow()]) plt.show()
adc2802c4a745e8a6adbf5930d61cd3fb707583b57e58921c239560044389214
""" ============ Findobj Demo ============ Recursively find all objects that match some criteria """ import numpy as np import matplotlib.pyplot as plt import matplotlib.text as text a = np.arange(0, 3, .02) b = np.arange(0, 3, .02) c = np.exp(a) d = c[::-1] fig, ax = plt.subplots() plt.plot(a, c, 'k--', a, d, 'k:', a, c + d, 'k') plt.legend(('Model length', 'Data length', 'Total message length'), loc='upper center', shadow=True) plt.ylim([-1, 20]) plt.grid(False) plt.xlabel('Model complexity --->') plt.ylabel('Message length --->') plt.title('Minimum Message Length') # match on arbitrary function def myfunc(x): return hasattr(x, 'set_color') and not hasattr(x, 'set_facecolor') for o in fig.findobj(myfunc): o.set_color('blue') # match on class instances for o in fig.findobj(text.Text): o.set_fontstyle('italic') plt.show()
0e161be305ddc262052935aa81897d87c576c7a4db42565ac4153f1c676b6663
""" =========== Cursor Demo =========== This example shows how to use Matplotlib to provide a data cursor. It uses Matplotlib to draw the cursor and may be a slow since this requires redrawing the figure with every mouse move. Faster cursoring is possible using native GUI drawing, as in :doc:`/gallery/user_interfaces/wxcursor_demo_sgskip`. The mpldatacursor__ and mplcursors__ third-party packages can be used to achieve a similar effect. __ https://github.com/joferkington/mpldatacursor __ https://github.com/anntzer/mplcursors """ import matplotlib.pyplot as plt import numpy as np class Cursor(object): def __init__(self, ax): self.ax = ax self.lx = ax.axhline(color='k') # the horiz line self.ly = ax.axvline(color='k') # the vert line # text location in axes coords self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes) def mouse_move(self, event): if not event.inaxes: return x, y = event.xdata, event.ydata # update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y)) self.ax.figure.canvas.draw() class SnaptoCursor(object): """ Like Cursor but the crosshair snaps to the nearest x, y point. For simplicity, this assumes that *x* is sorted. """ def __init__(self, ax, x, y): self.ax = ax self.lx = ax.axhline(color='k') # the horiz line self.ly = ax.axvline(color='k') # the vert line self.x = x self.y = y # text location in axes coords self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes) def mouse_move(self, event): if not event.inaxes: return x, y = event.xdata, event.ydata indx = min(np.searchsorted(self.x, x), len(self.x) - 1) x = self.x[indx] y = self.y[indx] # update the line positions self.lx.set_ydata(y) self.ly.set_xdata(x) self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y)) print('x=%1.2f, y=%1.2f' % (x, y)) self.ax.figure.canvas.draw() t = np.arange(0.0, 1.0, 0.01) s = np.sin(2 * 2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s, 'o') cursor = Cursor(ax) fig.canvas.mpl_connect('motion_notify_event', cursor.mouse_move) fig, ax = plt.subplots() ax.plot(t, s, 'o') snap_cursor = SnaptoCursor(ax, t, s) fig.canvas.mpl_connect('motion_notify_event', snap_cursor.mouse_move) plt.show()
fd9936ee25ef687208c42711f8a4ca8f0bea8eb40301446e9fa50f5771a64303
""" =============== Demo Agg Filter =============== """ import matplotlib.pyplot as plt import numpy as np import matplotlib.cm as cm import matplotlib.transforms as mtransforms from matplotlib.colors import LightSource from matplotlib.artist import Artist 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 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 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): ny, nx, depth = im.shape alpha = np.pad(im[..., -1], self.pixels, "constant") alpha2 = np.clip(smooth2d(alpha, self.pixels/72.*dpi) * 5, 0, 1) new_im = np.empty((*alpha2.shape, 4)) new_im[:, :, -1] = alpha2 new_im[:, :, :-1] = self.color offsetx, offsety = -self.pixels, -self.pixels return new_im, offsetx, offsety 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() 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 = np.exp(-X**2 - Y**2) Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) Z = (Z1 - Z2) * 2 # 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], # label every second level inline=1, fmt='%1.1f', fontsize=11) # change clabel color to black from matplotlib.patheffects import Normal for t in cl: t.set_color("k") # to force TextPath (i.e., same font in all backends) t.set_path_effects([Normal()]) # 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): # copied 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): # Copied 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_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 __name__ == "__main__": plt.figure(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()
f4d5c60af374af73ac940e9b7ce84617758a107ba12946366c0e8522748a917a
""" ====================== Geographic Projections ====================== This shows 4 possible projections using subplot. Matplotlib also supports `Basemaps Toolkit <https://matplotlib.org/basemap>`_ and `Cartopy <http://scitools.org.uk/cartopy>`_ for geographic projections. """ import matplotlib.pyplot as plt ############################################################################### plt.figure() plt.subplot(111, projection="aitoff") plt.title("Aitoff") plt.grid(True) ############################################################################### plt.figure() plt.subplot(111, projection="hammer") plt.title("Hammer") plt.grid(True) ############################################################################### plt.figure() plt.subplot(111, projection="lambert") plt.title("Lambert") plt.grid(True) ############################################################################### plt.figure() plt.subplot(111, projection="mollweide") plt.title("Mollweide") plt.grid(True) plt.show()
479423278e0c2cc2d5424ba86ea0915dc7b5dafab5565600b86f91537c816eb8
""" ================= Placing Colorbars ================= Colorbars indicate the quantitative extent of image data. Placing in a figure is non-trivial because room needs to be made for them. The simplest case is just attaching a colorbar to each axes: """ import matplotlib.pyplot as plt import numpy as np fig, axs = plt.subplots(2, 2) cm = ['RdBu_r', 'viridis'] for col in range(2): for row in range(2): ax = axs[row, col] pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), cmap=cm[col]) fig.colorbar(pcm, ax=ax) plt.show() ###################################################################### # The first column has the same type of data in both rows, so it may # be desirable to combine the colorbar which we do by calling # `.Figure.colorbar` with a list of axes instead of a single axes. fig, axs = plt.subplots(2, 2) cm = ['RdBu_r', 'viridis'] for col in range(2): for row in range(2): ax = axs[row, col] pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1), cmap=cm[col]) fig.colorbar(pcm, ax=axs[:, col], shrink=0.6) plt.show() ###################################################################### # Relatively complicated colorbar layouts are possible using this # paradigm. Note that this example works far better with # ``constrained_layout=True`` fig, axs = plt.subplots(3, 3, constrained_layout=True) for ax in axs.flat: pcm = ax.pcolormesh(np.random.random((20, 20))) fig.colorbar(pcm, ax=axs[0, :2], shrink=0.6, location='bottom') fig.colorbar(pcm, ax=[axs[0, 2]], location='bottom') fig.colorbar(pcm, ax=axs[1:, :], location='right', shrink=0.6) fig.colorbar(pcm, ax=[axs[2, 1]], location='left') plt.show()
718407617c4a2e5baeea2855f0ddb737280932dd4cde03d196161d09eb013346
""" ================================= Different scales on the same axes ================================= Demo of how to display two scales on the left and right y axis. This example uses the Fahrenheit and Celsius scales. """ import matplotlib.pyplot as plt import numpy as np def fahrenheit2celsius(temp): """ Returns temperature in Celsius. """ return (5. / 9.) * (temp - 32) def convert_ax_c_to_celsius(ax_f): """ Update second axis according with first axis. """ y1, y2 = ax_f.get_ylim() ax_c.set_ylim(fahrenheit2celsius(y1), fahrenheit2celsius(y2)) ax_c.figure.canvas.draw() fig, ax_f = plt.subplots() ax_c = ax_f.twinx() # automatically update ylim of ax2 when ylim of ax1 changes. ax_f.callbacks.connect("ylim_changed", convert_ax_c_to_celsius) ax_f.plot(np.linspace(-40, 120, 100)) ax_f.set_xlim(0, 100) ax_f.set_title('Two scales: Fahrenheit and Celsius') ax_f.set_ylabel('Fahrenheit') ax_c.set_ylabel('Celsius') plt.show()
7319373b83ae620fb6aa6452776ab76e022e73eb552aad36b4a26d1ead942edb
""" ============ Figure Title ============ Create a figure with separate subplot titles and a centered figure title. """ import matplotlib.pyplot as plt import numpy as np def f(t): s1 = np.cos(2*np.pi*t) e1 = np.exp(-t) return s1 * e1 t1 = np.arange(0.0, 5.0, 0.1) t2 = np.arange(0.0, 5.0, 0.02) t3 = np.arange(0.0, 2.0, 0.01) fig, axs = plt.subplots(2, 1, constrained_layout=True) axs[0].plot(t1, f(t1), 'o', t2, f(t2), '-') axs[0].set_title('subplot 1') axs[0].set_xlabel('distance (m)') axs[0].set_ylabel('Damped oscillation') fig.suptitle('This is a somewhat long figure title', fontsize=16) axs[1].plot(t3, np.cos(2*np.pi*t3), '--') axs[1].set_xlabel('time (s)') axs[1].set_title('subplot 2') axs[1].set_ylabel('Undamped') plt.show()
0162a48af151298abcbf14e37c7f479862771464805c062f5b95ebc1526acce1
""" =========== Broken Axis =========== Broken axis example, where the y-axis will have a portion cut out. """ import matplotlib.pyplot as plt import numpy as np # 30 points between [0, 0.2) originally made using np.random.rand(30)*.2 pts = np.array([ 0.015, 0.166, 0.133, 0.159, 0.041, 0.024, 0.195, 0.039, 0.161, 0.018, 0.143, 0.056, 0.125, 0.096, 0.094, 0.051, 0.043, 0.021, 0.138, 0.075, 0.109, 0.195, 0.050, 0.074, 0.079, 0.155, 0.020, 0.010, 0.061, 0.008]) # Now let's make two outlier points which are far away from everything. pts[[3, 14]] += .8 # If we were to simply plot pts, we'd lose most of the interesting # details due to the outliers. So let's 'break' or 'cut-out' the y-axis # into two portions - use the top (ax) for the outliers, and the bottom # (ax2) for the details of the majority of our data f, (ax, ax2) = plt.subplots(2, 1, sharex=True) # plot the same data on both axes ax.plot(pts) ax2.plot(pts) # zoom-in / limit the view to different portions of the data ax.set_ylim(.78, 1.) # outliers only ax2.set_ylim(0, .22) # most of the data # hide the spines between ax and ax2 ax.spines['bottom'].set_visible(False) ax2.spines['top'].set_visible(False) ax.xaxis.tick_top() ax.tick_params(labeltop=False) # don't put tick labels at the top ax2.xaxis.tick_bottom() # This looks pretty good, and was fairly painless, but you can get that # cut-out diagonal lines look with just a bit more work. The important # thing to know here is that in axes coordinates, which are always # between 0-1, spine endpoints are at these locations (0,0), (0,1), # (1,0), and (1,1). Thus, we just need to put the diagonals in the # appropriate corners of each of our axes, and so long as we use the # right transform and disable clipping. d = .015 # how big to make the diagonal lines in axes coordinates # arguments to pass to plot, just so we don't keep repeating them kwargs = dict(transform=ax.transAxes, color='k', clip_on=False) ax.plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal ax.plot((1 - d, 1 + d), (-d, +d), **kwargs) # top-right diagonal kwargs.update(transform=ax2.transAxes) # switch to the bottom axes ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) # bottom-right diagonal # What's cool about this is that now if we vary the distance between # ax and ax2 via f.subplots_adjust(hspace=...) or plt.subplot_tool(), # the diagonal lines will move accordingly, and stay right at the tips # of the spines they are 'breaking' plt.show()
e1a598cdf1c1d2a3c68284811411d549103676c640c549eff1d77e8a33e73520
""" ================= Multiple subplots ================= Simple demo with multiple subplots. """ import numpy as np import matplotlib.pyplot as plt x1 = np.linspace(0.0, 5.0) x2 = np.linspace(0.0, 2.0) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) y2 = np.cos(2 * np.pi * x2) plt.subplot(2, 1, 1) plt.plot(x1, y1, 'o-') plt.title('A tale of 2 subplots') plt.ylabel('Damped oscillation') plt.subplot(2, 1, 2) plt.plot(x2, y2, '.-') plt.xlabel('time (s)') plt.ylabel('Undamped') plt.show()
4a1579c7986f3fcdd2275fce55d03d31374738ec19926ba290dad351155e2ba3
""" ============== Secondary Axis ============== Sometimes we want as secondary axis on a plot, for instance to convert radians to degrees on the same plot. We can do this by making a child axes with only one axis visible via `.Axes.axes.secondary_xaxis` and `.Axes.axes.secondary_yaxis`. This secondary axis can have a different scale than the main axis by providing both a forward and an inverse conversion function in a tuple to the ``functions`` kwarg: """ import matplotlib.pyplot as plt import numpy as np import datetime import matplotlib.dates as mdates from matplotlib.transforms import Transform from matplotlib.ticker import ( AutoLocator, AutoMinorLocator) fig, ax = plt.subplots(constrained_layout=True) x = np.arange(0, 360, 1) y = np.sin(2 * x * np.pi / 180) ax.plot(x, y) ax.set_xlabel('angle [degrees]') ax.set_ylabel('signal') ax.set_title('Sine wave') def deg2rad(x): return x * np.pi / 180 def rad2deg(x): return x * 180 / np.pi secax = ax.secondary_xaxis('top', functions=(deg2rad, rad2deg)) secax.set_xlabel('angle [rad]') plt.show() ########################################################################### # Here is the case of converting from wavenumber to wavelength in a # log-log scale. # # .. note :: # # In this case, the xscale of the parent is logarithmic, so the child is # made logarithmic as well. fig, ax = plt.subplots(constrained_layout=True) x = np.arange(0.02, 1, 0.02) np.random.seed(19680801) y = np.random.randn(len(x)) ** 2 ax.loglog(x, y) ax.set_xlabel('f [Hz]') ax.set_ylabel('PSD') ax.set_title('Random spectrum') def forward(x): return 1 / x def inverse(x): return 1 / x secax = ax.secondary_xaxis('top', functions=(forward, inverse)) secax.set_xlabel('period [s]') plt.show() ########################################################################### # Sometime we want to relate the axes in a transform that is ad-hoc from # the data, and is derived empirically. In that case we can set the # forward and inverse transforms functions to be linear interpolations from the # one data set to the other. fig, ax = plt.subplots(constrained_layout=True) xdata = np.arange(1, 11, 0.4) ydata = np.random.randn(len(xdata)) ax.plot(xdata, ydata, label='Plotted data') xold = np.arange(0, 11, 0.2) # fake data set relating x co-ordinate to another data-derived co-ordinate. # xnew must be monotonic, so we sort... xnew = np.sort(10 * np.exp(-xold / 4) + np.random.randn(len(xold)) / 3) ax.plot(xold[3:], xnew[3:], label='Transform data') ax.set_xlabel('X [m]') ax.legend() def forward(x): return np.interp(x, xold, xnew) def inverse(x): return np.interp(x, xnew, xold) secax = ax.secondary_xaxis('top', functions=(forward, inverse)) secax.xaxis.set_minor_locator(AutoMinorLocator()) secax.set_xlabel('$X_{other}$') plt.show() ########################################################################### # A final example translates np.datetime64 to yearday on the x axis and # from Celsius to Farenheit on the y axis: dates = [datetime.datetime(2018, 1, 1) + datetime.timedelta(hours=k * 6) for k in range(240)] temperature = np.random.randn(len(dates)) fig, ax = plt.subplots(constrained_layout=True) ax.plot(dates, temperature) ax.set_ylabel(r'$T\ [^oC]$') plt.xticks(rotation=70) def date2yday(x): """ x is in matplotlib datenums, so they are floats. """ y = x - mdates.date2num(datetime.datetime(2018, 1, 1)) return y def yday2date(x): """ return a matplotlib datenum (x is days since start of year) """ y = x + mdates.date2num(datetime.datetime(2018, 1, 1)) return y secaxx = ax.secondary_xaxis('top', functions=(date2yday, yday2date)) secaxx.set_xlabel('yday [2018]') def CtoF(x): return x * 1.8 + 32 def FtoC(x): return (x - 32) / 1.8 secaxy = ax.secondary_yaxis('right', functions=(CtoF, FtoC)) secaxy.set_ylabel(r'$T\ [^oF]$') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown in this example: import matplotlib matplotlib.axes.Axes.secondary_xaxis matplotlib.axes.Axes.secondary_yaxis
509d0117664a7ea94efc0c6b4e1327cb54607a6d6ff97aa683c96a2eb75ef99e
""" ======================================================= Using Gridspec to make multi-column/row subplot layouts ======================================================= `.GridSpec` is a flexible way to layout subplot grids. Here is an example with a 3x3 grid, and axes spanning all three columns, two columns, and two rows. """ import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec def format_axes(fig): for i, ax in enumerate(fig.axes): ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center") ax.tick_params(labelbottom=False, labelleft=False) fig = plt.figure(constrained_layout=True) gs = GridSpec(3, 3, figure=fig) ax1 = fig.add_subplot(gs[0, :]) # identical to ax1 = plt.subplot(gs.new_subplotspec((0, 0), colspan=3)) ax2 = fig.add_subplot(gs[1, :-1]) ax3 = fig.add_subplot(gs[1:, -1]) ax4 = fig.add_subplot(gs[-1, 0]) ax5 = fig.add_subplot(gs[-1, -2]) fig.suptitle("GridSpec") format_axes(fig) plt.show()
99aa101531d13f4f42fa4c310875da9e31954ae4eb1cf346afdac80853172da2
""" =================== Custom Figure Class =================== You can pass a custom Figure constructor to figure if you want to derive from the default Figure. This simple example creates a figure with a figure title. """ import matplotlib.pyplot as plt from matplotlib.figure import Figure class MyFigure(Figure): def __init__(self, *args, figtitle='hi mom', **kwargs): """ custom kwarg figtitle is a figure title """ super().__init__(*args, **kwargs) self.text(0.5, 0.95, figtitle, ha='center') fig = plt.figure(FigureClass=MyFigure, figtitle='my title') ax = fig.subplots() ax.plot([1, 2, 3]) plt.show()
093e9ce26756c45fd0238d236b3c3cee2bd7144f5e0488476664923e4d63afb1
""" =============================== Resizing axes with tight layout =============================== `~.figure.Figure.tight_layout` attempts to resize subplots in a figure so that there are no overlaps between axes objects and labels on the axes. See :doc:`/tutorials/intermediate/tight_layout_guide` for more details and :doc:`/tutorials/intermediate/constrainedlayout_guide` for an alternative. """ import matplotlib.pyplot as plt import itertools import warnings fontsizes = itertools.cycle([8, 16, 24, 32]) def example_plot(ax): ax.plot([1, 2]) ax.set_xlabel('x-label', fontsize=next(fontsizes)) ax.set_ylabel('y-label', fontsize=next(fontsizes)) ax.set_title('Title', fontsize=next(fontsizes)) ############################################################################### fig, ax = plt.subplots() example_plot(ax) plt.tight_layout() ############################################################################### fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) plt.tight_layout() ############################################################################### fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1) example_plot(ax1) example_plot(ax2) plt.tight_layout() ############################################################################### fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2) example_plot(ax1) example_plot(ax2) plt.tight_layout() ############################################################################### fig, axes = plt.subplots(nrows=3, ncols=3) for row in axes: for ax in row: example_plot(ax) plt.tight_layout() ############################################################################### fig = plt.figure() ax1 = plt.subplot(221) ax2 = plt.subplot(223) ax3 = plt.subplot(122) example_plot(ax1) example_plot(ax2) example_plot(ax3) plt.tight_layout() ############################################################################### fig = plt.figure() ax1 = plt.subplot2grid((3, 3), (0, 0)) ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2) ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2) ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) example_plot(ax1) example_plot(ax2) example_plot(ax3) example_plot(ax4) plt.tight_layout() plt.show() ############################################################################### fig = plt.figure() gs1 = fig.add_gridspec(3, 1) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1]) ax3 = fig.add_subplot(gs1[2]) example_plot(ax1) example_plot(ax2) example_plot(ax3) gs1.tight_layout(fig, rect=[None, None, 0.45, None]) gs2 = fig.add_gridspec(2, 1) ax4 = fig.add_subplot(gs2[0]) ax5 = fig.add_subplot(gs2[1]) example_plot(ax4) example_plot(ax5) with warnings.catch_warnings(): # gs2.tight_layout cannot handle the subplots from the first gridspec # (gs1), so it will raise a warning. We are going to match the gridspecs # manually so we can filter the warning away. warnings.simplefilter("ignore", UserWarning) gs2.tight_layout(fig, rect=[0.45, None, None, None]) # now match the top and bottom of two gridspecs. top = min(gs1.top, gs2.top) bottom = max(gs1.bottom, gs2.bottom) gs1.update(top=top, bottom=bottom) gs2.update(top=top, bottom=bottom) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown in this example: import matplotlib matplotlib.pyplot.tight_layout matplotlib.figure.Figure.tight_layout matplotlib.figure.Figure.add_gridspec matplotlib.figure.Figure.add_subplot matplotlib.pyplot.subplot2grid
8efd03c5f0ec1d9806a5ce00ec27b7ce06ed445998cccfbfedc7ee69574ebf6b
""" ================== Multiple Figs Demo ================== Working with multiple figure windows and subplots """ import matplotlib.pyplot as plt import numpy as np t = np.arange(0.0, 2.0, 0.01) s1 = np.sin(2*np.pi*t) s2 = np.sin(4*np.pi*t) ############################################################################### # Create figure 1 plt.figure(1) plt.subplot(211) plt.plot(t, s1) plt.subplot(212) plt.plot(t, 2*s1) ############################################################################### # Create figure 2 plt.figure(2) plt.plot(t, s2) ############################################################################### # Now switch back to figure 1 and make some changes plt.figure(1) plt.subplot(211) plt.plot(t, s2, 's') ax = plt.gca() ax.set_xticklabels([]) plt.show()
5559755d47352d45667f69cdb42b45b601448754064f9086305f8b3a1b6dad37
""" ================ Nested Gridspecs ================ GridSpecs can be nested, so that a subplot from a parent GridSpec can set the position for a nested grid of subplots. """ import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec def format_axes(fig): for i, ax in enumerate(fig.axes): ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center") ax.tick_params(labelbottom=False, labelleft=False) # gridspec inside gridspec f = plt.figure() gs0 = gridspec.GridSpec(1, 2, figure=f) gs00 = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=gs0[0]) ax1 = f.add_subplot(gs00[:-1, :]) ax2 = f.add_subplot(gs00[-1, :-1]) ax3 = f.add_subplot(gs00[-1, -1]) # the following syntax does the same as the GridSpecFromSubplotSpec call above: gs01 = gs0[1].subgridspec(3, 3) ax4 = f.add_subplot(gs01[:, :-1]) ax5 = f.add_subplot(gs01[:-1, -1]) ax6 = f.add_subplot(gs01[-1, -1]) plt.suptitle("GridSpec Inside GridSpec") format_axes(f) plt.show()
ae49f764bf57d2dd816d25e81e7a9af171afced48f7e354b89590c17e1e4b9a5
""" =============== Subplots Adjust =============== Adjusting the spacing of margins and subplots using :func:`~matplotlib.pyplot.subplots_adjust`. """ import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) plt.subplot(211) plt.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r) plt.subplot(212) plt.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r) plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9) cax = plt.axes([0.85, 0.1, 0.075, 0.8]) plt.colorbar(cax=cax) plt.show()
aed42c0821fbf65729f96657c07810a198cc8ff4fa5307f2cde7183485f5560f
""" =============== Aligning Labels =============== Aligning xlabel and ylabel using `Figure.align_xlabels` and `Figure.align_ylabels` `Figure.align_labels` wraps these two functions. Note that the xlabel "XLabel1 1" would normally be much closer to the x-axis, and "YLabel1 0" would be much closer to the y-axis of their respective axes. """ import matplotlib.pyplot as plt import numpy as np import matplotlib.gridspec as gridspec fig = plt.figure(tight_layout=True) gs = gridspec.GridSpec(2, 2) ax = fig.add_subplot(gs[0, :]) ax.plot(np.arange(0, 1e6, 1000)) ax.set_ylabel('YLabel0') ax.set_xlabel('XLabel0') for i in range(2): ax = fig.add_subplot(gs[1, i]) ax.plot(np.arange(1., 0., -0.1) * 2000., np.arange(1., 0., -0.1)) ax.set_ylabel('YLabel1 %d' % i) ax.set_xlabel('XLabel1 %d' % i) if i == 0: for tick in ax.get_xticklabels(): tick.set_rotation(55) fig.align_labels() # same as fig.align_xlabels(); fig.align_ylabels() plt.show()
94bb41476ab2bd17d3b1c2e30c57484df70679e87841ac11d736c07e1c9aded5
""" ================ Axes Zoom Effect ================ """ from matplotlib.transforms import ( Bbox, TransformedBbox, blended_transform_factory) from mpl_toolkits.axes_grid1.inset_locator import ( BboxPatch, BboxConnector, BboxConnectorPatch) def connect_bbox(bbox1, bbox2, loc1a, loc2a, loc1b, loc2b, prop_lines, prop_patches=None): if prop_patches is None: prop_patches = { **prop_lines, "alpha": prop_lines.get("alpha", 1) * 0.2, } c1 = BboxConnector(bbox1, bbox2, loc1=loc1a, loc2=loc2a, **prop_lines) c1.set_clip_on(False) c2 = BboxConnector(bbox1, bbox2, loc1=loc1b, loc2=loc2b, **prop_lines) c2.set_clip_on(False) bbox_patch1 = BboxPatch(bbox1, **prop_patches) bbox_patch2 = BboxPatch(bbox2, **prop_patches) p = BboxConnectorPatch(bbox1, bbox2, # loc1a=3, loc2a=2, loc1b=4, loc2b=1, loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b, **prop_patches) p.set_clip_on(False) return c1, c2, bbox_patch1, bbox_patch2, p def zoom_effect01(ax1, ax2, xmin, xmax, **kwargs): """ ax1 : the main axes ax1 : the zoomed axes (xmin,xmax) : the limits of the colored area in both plot axes. connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will be marked. The keywords parameters will be used ti create patches. """ trans1 = blended_transform_factory(ax1.transData, ax1.transAxes) trans2 = blended_transform_factory(ax2.transData, ax2.transAxes) bbox = Bbox.from_extents(xmin, 0, xmax, 1) mybbox1 = TransformedBbox(bbox, trans1) mybbox2 = TransformedBbox(bbox, trans2) prop_patches = {**kwargs, "ec": "none", "alpha": 0.2} c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox( mybbox1, mybbox2, loc1a=3, loc2a=2, loc1b=4, loc2b=1, prop_lines=kwargs, prop_patches=prop_patches) ax1.add_patch(bbox_patch1) ax2.add_patch(bbox_patch2) ax2.add_patch(c1) ax2.add_patch(c2) ax2.add_patch(p) return c1, c2, bbox_patch1, bbox_patch2, p def zoom_effect02(ax1, ax2, **kwargs): """ ax1 : the main axes ax1 : the zoomed axes Similar to zoom_effect01. The xmin & xmax will be taken from the ax1.viewLim. """ tt = ax1.transScale + (ax1.transLimits + ax2.transAxes) trans = blended_transform_factory(ax2.transData, tt) mybbox1 = ax1.bbox mybbox2 = TransformedBbox(ax1.viewLim, trans) prop_patches = {**kwargs, "ec": "none", "alpha": 0.2} c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox( mybbox1, mybbox2, loc1a=3, loc2a=2, loc1b=4, loc2b=1, prop_lines=kwargs, prop_patches=prop_patches) ax1.add_patch(bbox_patch1) ax2.add_patch(bbox_patch2) ax2.add_patch(c1) ax2.add_patch(c2) ax2.add_patch(p) return c1, c2, bbox_patch1, bbox_patch2, p import matplotlib.pyplot as plt plt.figure(figsize=(5, 5)) ax1 = plt.subplot(221) ax2 = plt.subplot(212) ax2.set_xlim(0, 1) ax2.set_xlim(0, 5) zoom_effect01(ax1, ax2, 0.2, 0.8) ax1 = plt.subplot(222) ax1.set_xlim(2, 3) ax2.set_xlim(0, 5) zoom_effect02(ax1, ax2) plt.show()
58459d7b587058f6e0c07f8b083a0f43f4e0db667b8c6a7dd55e1e57dd63148b
""" =============== Axis Equal Demo =============== How to set and adjust plots with equal axis ratios. """ import matplotlib.pyplot as plt import numpy as np # Plot circle of radius 3. an = np.linspace(0, 2 * np.pi, 100) fig, axs = plt.subplots(2, 2) axs[0, 0].plot(3 * np.cos(an), 3 * np.sin(an)) axs[0, 0].set_title('not equal, looks like ellipse', fontsize=10) axs[0, 1].plot(3 * np.cos(an), 3 * np.sin(an)) axs[0, 1].axis('equal') axs[0, 1].set_title('equal, looks like circle', fontsize=10) axs[1, 0].plot(3 * np.cos(an), 3 * np.sin(an)) axs[1, 0].axis('equal') axs[1, 0].axis([-3, 3, -3, 3]) axs[1, 0].set_title('still a circle, even after changing limits', fontsize=10) axs[1, 1].plot(3 * np.cos(an), 3 * np.sin(an)) axs[1, 1].set_aspect('equal', 'box') axs[1, 1].set_title('still a circle, auto-adjusted data limits', fontsize=10) fig.tight_layout() plt.show()
f41b2b523400e630234d905723c9e2e781c351f62277d0def3b4fe561b95439d
""" ========================== Creating adjacent subplots ========================== To create plots that share a common axis (visually) you can set the hspace between the subplots to zero. Passing sharex=True when creating the subplots will automatically turn off all x ticks and labels except those on the bottom axis. In this example the plots share a common x axis but you can follow the same logic to supply a common y axis. """ import matplotlib.pyplot as plt import numpy as np t = np.arange(0.0, 2.0, 0.01) s1 = np.sin(2 * np.pi * t) s2 = np.exp(-t) s3 = s1 * s2 fig, axs = plt.subplots(3, 1, sharex=True) # Remove horizontal space between axes fig.subplots_adjust(hspace=0) # Plot each graph, and manually set the y tick values axs[0].plot(t, s1) axs[0].set_yticks(np.arange(-0.9, 1.0, 0.4)) axs[0].set_ylim(-1, 1) axs[1].plot(t, s2) axs[1].set_yticks(np.arange(0.1, 1.0, 0.2)) axs[1].set_ylim(0, 1) axs[2].plot(t, s3) axs[2].set_yticks(np.arange(-0.9, 1.0, 0.4)) axs[2].set_ylim(-1, 1) plt.show()
280284f5ac2590f4c4c253eb7d9848d53c0f97407e448aedec7a23c9d7feb2ee
""" ========= Axes Demo ========= Example use of ``plt.axes`` to create inset axes within the main plot axes. """ import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) # create some data to use for the plot dt = 0.001 t = np.arange(0.0, 10.0, dt) r = np.exp(-t[:1000] / 0.05) # impulse response x = np.random.randn(len(t)) s = np.convolve(x, r)[:len(x)] * dt # colored noise # the main axes is subplot(111) by default plt.plot(t, s) plt.axis([0, 1, 1.1 * np.min(s), 2 * np.max(s)]) plt.xlabel('time (s)') plt.ylabel('current (nA)') plt.title('Gaussian colored noise') # this is an inset axes over the main axes a = plt.axes([.65, .6, .2, .2], facecolor='k') n, bins, patches = plt.hist(s, 400, density=True) plt.title('Probability') plt.xticks([]) plt.yticks([]) # this is another inset axes over the main axes a = plt.axes([0.2, 0.6, .2, .2], facecolor='k') plt.plot(t[:len(r)], r) plt.title('Impulse response') plt.xlim(0, 0.2) plt.xticks([]) plt.yticks([]) plt.show()
9382e8038aded4d1d29ac3cf3b18edf5ed454040f7f5bd132de1cf361dbb7308
""" =========================== Plots with different scales =========================== Two plots on the same axes with different left and right scales. The trick is to use *two different axes* that share the same *x* axis. You can use separate `matplotlib.ticker` formatters and locators as desired since the two axes are independent. Such axes are generated by calling the :meth:`.Axes.twinx` method. Likewise, :meth:`.Axes.twiny` is available to generate axes that share a *y* axis but have different top and bottom scales. """ import numpy as np import matplotlib.pyplot as plt # Create some mock data t = np.arange(0.01, 10.0, 0.01) data1 = np.exp(t) data2 = np.sin(2 * np.pi * t) fig, ax1 = plt.subplots() color = 'tab:red' ax1.set_xlabel('time (s)') ax1.set_ylabel('exp', color=color) ax1.plot(t, data1, color=color) ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis color = 'tab:blue' ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1 ax2.plot(t, data2, color=color) ax2.tick_params(axis='y', labelcolor=color) fig.tight_layout() # otherwise the right y-label is slightly clipped plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.twinx matplotlib.axes.Axes.twiny matplotlib.axes.Axes.tick_params
a65934b4a25bfeefc232f30857c4bd8aaff739d5f4972d1f190d4faac7871a8b
""" =============== Subplot Toolbar =============== Matplotlib has a toolbar available for adjusting subplot spacing. """ import matplotlib.pyplot as plt import numpy as np fig, axs = plt.subplots(2, 2) axs[0, 0].imshow(np.random.random((100, 100))) axs[0, 1].imshow(np.random.random((100, 100))) axs[1, 0].imshow(np.random.random((100, 100))) axs[1, 1].imshow(np.random.random((100, 100))) plt.subplot_tool() plt.show()
ab4e1d04375985e1156c491f28a3c6791a09f3ce3a8d10f139db9722f9af5b4c
""" ================ Shared Axis Demo ================ You can share the x or y axis limits for one axis with another by passing an axes instance as a sharex or sharey kwarg. Changing the axis limits on one axes will be reflected automatically in the other, and vice-versa, so when you navigate with the toolbar the axes will follow each other on their shared axes. Ditto for changes in the axis scaling (e.g., log vs linear). However, it is possible to have differences in tick labeling, e.g., you can selectively turn off the tick labels on one axes. The example below shows how to customize the tick labels on the various axes. Shared axes share the tick locator, tick formatter, view limits, and transformation (e.g., log, linear). But the ticklabels themselves do not share properties. This is a feature and not a bug, because you may want to make the tick labels smaller on the upper axes, e.g., in the example below. If you want to turn off the ticklabels for a given axes (e.g., on subplot(211) or subplot(212), you cannot do the standard trick:: setp(ax2, xticklabels=[]) because this changes the tick Formatter, which is shared among all axes. But you can alter the visibility of the labels, which is a property:: setp(ax2.get_xticklabels(), visible=False) """ import matplotlib.pyplot as plt import numpy as np t = np.arange(0.01, 5.0, 0.01) s1 = np.sin(2 * np.pi * t) s2 = np.exp(-t) s3 = np.sin(4 * np.pi * t) ax1 = plt.subplot(311) plt.plot(t, s1) plt.setp(ax1.get_xticklabels(), fontsize=6) # share x only ax2 = plt.subplot(312, sharex=ax1) plt.plot(t, s2) # make these tick labels invisible plt.setp(ax2.get_xticklabels(), visible=False) # share x and y ax3 = plt.subplot(313, sharex=ax1, sharey=ax1) plt.plot(t, s3) plt.xlim(0.01, 5.0) plt.show()
763278297083916eb7d3b6d3edf6666b1056417c145662b798e77cb13497923d
""" ================================================== Combining two subplots using subplots and GridSpec ================================================== Sometimes we want to combine two subplots in an axes layout created with `~.Figure.subplots`. We can get the `~.gridspec.GridSpec` from the axes and then remove the covered axes and fill the gap with a new bigger axes. Here we create a layout with the bottom two axes in the last column combined. See also :doc:`/tutorials/intermediate/gridspec`. """ import matplotlib.pyplot as plt fig, axs = plt.subplots(ncols=3, nrows=3) gs = axs[1, 2].get_gridspec() # remove the underlying axes for ax in axs[1:, -1]: ax.remove() axbig = fig.add_subplot(gs[1:, -1]) axbig.annotate('Big Axes \nGridSpec[1:, -1]', (0.1, 0.5), xycoords='axes fraction', va='center') fig.tight_layout() plt.show()
618b6e64d36adf14a64fd9858e3e6cca845008d7d76f2912b1fb76b030035b6f
""" =========== Invert Axes =========== You can use decreasing axes by flipping the normal order of the axis limits """ import matplotlib.pyplot as plt import numpy as np t = np.arange(0.01, 5.0, 0.01) s = np.exp(-t) plt.plot(t, s) plt.xlim(5, 0) # decreasing time plt.xlabel('decreasing time (s)') plt.ylabel('voltage (mV)') plt.title('Should be growing...') plt.grid(True) plt.show()
f6d6c054fd9d2a9cb95e8f46413ad2c88cf3f44134aee015644d86a5aed9c10f
""" ===================================== Resizing axes with constrained layout ===================================== Constrained layout attempts to resize subplots in a figure so that there are no overlaps between axes objects and labels on the axes. See :doc:`/tutorials/intermediate/constrainedlayout_guide` for more details and :doc:`/tutorials/intermediate/tight_layout_guide` for an alternative. """ import matplotlib.pyplot as plt def example_plot(ax): ax.plot([1, 2]) ax.set_xlabel('x-label', fontsize=12) ax.set_ylabel('y-label', fontsize=12) ax.set_title('Title', fontsize=14) ############################################################################### # If we don't use constrained_layout, then labels overlap the axes fig, axs = plt.subplots(nrows=2, ncols=2, constrained_layout=False) for ax in axs.flatten(): example_plot(ax) ############################################################################### # adding ``constrained_layout=True`` automatically adjusts. fig, axs = plt.subplots(nrows=2, ncols=2, constrained_layout=True) for ax in axs.flatten(): example_plot(ax) ############################################################################### # Below is a more complicated example using nested gridspecs. fig = plt.figure(constrained_layout=True) import matplotlib.gridspec as gridspec gs0 = gridspec.GridSpec(1, 2, figure=fig) gs1 = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=gs0[0]) for n in range(3): ax = fig.add_subplot(gs1[n]) example_plot(ax) gs2 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs0[1]) for n in range(2): ax = fig.add_subplot(gs2[n]) example_plot(ax) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown in this example: import matplotlib matplotlib.gridspec.GridSpec matplotlib.gridspec.GridSpecFromSubplotSpec
e04a76680dd1c154770d1a1ada3a69e18e3fd178fa0168db3b7a219a38c155ae
""" ===================================================================== Zooming in and out using Axes.margins and the subject of "stickiness" ===================================================================== The first figure in this example shows how to zoom in and out of a plot using `~.Axes.margins` instead of `~.Axes.set_xlim` and `~.Axes.set_ylim`. The second figure demonstrates the concept of edge "stickiness" introduced by certain methods and artists and how to effectively work around that. """ import numpy as np import matplotlib.pyplot as plt def f(t): return np.exp(-t) * np.cos(2*np.pi*t) t1 = np.arange(0.0, 3.0, 0.01) ax1 = plt.subplot(212) ax1.margins(0.05) # Default margin is 0.05, value 0 means fit ax1.plot(t1, f(t1)) ax2 = plt.subplot(221) ax2.margins(2, 2) # Values >0.0 zoom out ax2.plot(t1, f(t1)) ax2.set_title('Zoomed out') ax3 = plt.subplot(222) ax3.margins(x=0, y=-0.25) # Values in (-0.5, 0.0) zooms in to center ax3.plot(t1, f(t1)) ax3.set_title('Zoomed in') plt.show() ############################################################################# # # On the "stickiness" of certain plotting methods # """"""""""""""""""""""""""""""""""""""""""""""" # # Some plotting functions make the axis limits "sticky" or immune to the will # of the `~.Axes.margins` methods. For instance, `~.Axes.imshow` and # `~.Axes.pcolor` expect the user to want the limits to be tight around the # pixels shown in the plot. If this behavior is not desired, you need to set # `~.Axes.use_sticky_edges` to `False`. Consider the following example: y, x = np.mgrid[:5, 1:6] poly_coords = [ (0.25, 2.75), (3.25, 2.75), (2.25, 0.75), (0.25, 0.75) ] fig, (ax1, ax2) = plt.subplots(ncols=2) # Here we set the stickiness of the axes object... # ax1 we'll leave as the default, which uses sticky edges # and we'll turn off stickiness for ax2 ax2.use_sticky_edges = False for ax, status in zip((ax1, ax2), ('Is', 'Is Not')): cells = ax.pcolor(x, y, x+y, cmap='inferno') # sticky ax.add_patch( plt.Polygon(poly_coords, color='forestgreen', alpha=0.5) ) # not sticky ax.margins(x=0.1, y=0.05) ax.set_aspect('equal') ax.set_title('{} Sticky'.format(status)) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods is shown # in this example: import matplotlib matplotlib.axes.Axes.margins matplotlib.pyplot.margins matplotlib.axes.Axes.use_sticky_edges matplotlib.axes.Axes.pcolor matplotlib.pyplot.pcolor matplotlib.pyplot.Polygon
b1e7e0ffbc49f7b443b0e753e3adf2fb46dfbe655162dc5d8570442326066422
""" ========== Axes Props ========== You can control the axis tick and grid properties """ import matplotlib.pyplot as plt import numpy as np t = np.arange(0.0, 2.0, 0.01) s = np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.grid(True, linestyle='-.') ax.tick_params(labelcolor='r', labelsize='medium', width=3) plt.show()
3c4c0cab8ab6a0ed01f3230b9c3a5411174e9a37345ad831973122efaf7914dc
""" ============ axhspan Demo ============ Create lines or rectangles that span the axes in either the horizontal or vertical direction. """ import numpy as np import matplotlib.pyplot as plt t = np.arange(-1, 2, .01) s = np.sin(2 * np.pi * t) plt.plot(t, s) # Draw a thick red hline at y=0 that spans the xrange plt.axhline(linewidth=8, color='#d62728') # Draw a default hline at y=1 that spans the xrange plt.axhline(y=1) # Draw a default vline at x=1 that spans the yrange plt.axvline(x=1) # Draw a thick blue vline at x=0 that spans the upper quadrant of the yrange plt.axvline(x=0, ymin=0.75, linewidth=8, color='#1f77b4') # Draw a default hline at y=.5 that spans the middle half of the axes plt.axhline(y=.5, xmin=0.25, xmax=0.75) plt.axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5) plt.axvspan(1.25, 1.55, facecolor='#2ca02c', alpha=0.5) plt.axis([-1, 2, -1, 2]) plt.show()
755a0ce994c4676696bda045b1532d43375f24cc76b1a7c307bf1fa471c47686
""" ================================================ Creating multiple subplots using ``plt.subplot`` ================================================ `.pyplot.subplots` creates a figure and a grid of subplots with a single call, while providing reasonable control over how the individual plots are created. For more advanced use cases you can use `.GridSpec` for a more general subplot layout or `.Figure.add_subplot` for adding subplots at arbitrary locations within the figure. """ # sphinx_gallery_thumbnail_number = 11 import matplotlib.pyplot as plt import numpy as np # Some example data to display x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2) ############################################################################### # A figure with just one subplot # """""""""""""""""""""""""""""" # # ``subplots()`` without arguments returns a `.Figure` and a single # `~.axes.Axes`. # # This is actually the simplest and recommended way of creating a single # Figure and Axes. fig, ax = plt.subplots() ax.plot(x, y) ax.set_title('A single plot') ############################################################################### # Stacking subplots in one direction # """""""""""""""""""""""""""""""""" # # The first two optional arguments of `.pyplot.subplots` define the number of # rows and columns of the subplot grid. # # When stacking in one direction only, the returned `axs` is a 1D numpy array # containing the list of created Axes. fig, axs = plt.subplots(2) fig.suptitle('Vertically stacked subplots') axs[0].plot(x, y) axs[1].plot(x, -y) ############################################################################### # If you are creating just a few Axes, it's handy to unpack them immediately to # dedicated variables for each Axes. That way, we can use ``ax1`` instead of # the more verbose ``axs[0]``. fig, (ax1, ax2) = plt.subplots(2) fig.suptitle('Vertically stacked subplots') ax1.plot(x, y) ax2.plot(x, -y) ############################################################################### # To obtain side-by-side subplots, pass parameters ``1, 2`` for one row and two # columns. fig, (ax1, ax2) = plt.subplots(1, 2) fig.suptitle('Horizontally stacked subplots') ax1.plot(x, y) ax2.plot(x, -y) ############################################################################### # Stacking subplots in two directions # """"""""""""""""""""""""""""""""""" # # When stacking in two directions, the returned `axs` is a 2D numpy array. # # If you have to set parameters for each subplot it's handy to iterate over # all subplots in a 2D grid using ``for ax in axs.flat:``. fig, axs = plt.subplots(2, 2) axs[0, 0].plot(x, y) axs[0, 0].set_title('Axis [0,0]') axs[0, 1].plot(x, y, 'tab:orange') axs[0, 1].set_title('Axis [0,1]') axs[1, 0].plot(x, -y, 'tab:green') axs[1, 0].set_title('Axis [1,0]') axs[1, 1].plot(x, -y, 'tab:red') axs[1, 1].set_title('Axis [1,1]') for ax in axs.flat: ax.set(xlabel='x-label', ylabel='y-label') # Hide x labels and tick labels for top plots and y ticks for right plots. for ax in axs.flat: ax.label_outer() ############################################################################### # You can use tuple-unpacking also in 2D to assign all subplots to dedicated # variables: fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) fig.suptitle('Sharing x per column, y per row') ax1.plot(x, y) ax2.plot(x, y**2, 'tab:orange') ax3.plot(x, -y, 'tab:green') ax4.plot(x, -y**2, 'tab:red') for ax in axs.flat: ax.label_outer() ############################################################################### # Sharing axes # """""""""""" # # By default, each Axes is scaled individually. Thus, if the ranges are # different the tick values of the subplots do not align. fig, (ax1, ax2) = plt.subplots(2) fig.suptitle('Axes values are scaled individually by default') ax1.plot(x, y) ax2.plot(x + 1, -y) ############################################################################### # You can use *sharex* or *sharey* to align the horizontal or vertical axis. fig, (ax1, ax2) = plt.subplots(2, sharex=True) fig.suptitle('Aligning x-axis using sharex') ax1.plot(x, y) ax2.plot(x + 1, -y) ############################################################################### # Setting *sharex* or *sharey* to ``True`` enables global sharing across the # whole grid, i.e. also the y-axes of vertically stacked subplots have the # same scale when using ``sharey=True``. fig, axs = plt.subplots(3, sharex=True, sharey=True) fig.suptitle('Sharing both axes') axs[0].plot(x, y ** 2) axs[1].plot(x, 0.3 * y, 'o') axs[2].plot(x, y, '+') ############################################################################### # For subplots that are sharing axes one set of tick labels is enough. Tick # labels of inner Axes are automatically removed by *sharex* and *sharey*. # Still there remains an unused empty space between the subplots. # # The parameter *gridspec_kw* of `.pyplot.subplots` controls the grid # properties (see also `.GridSpec`). For example, we can reduce the height # between vertical subplots using ``gridspec_kw={'hspace': 0}``. # # `.label_outer` is a handy method to remove labels and ticks from subplots # that are not at the edge of the grid. fig, axs = plt.subplots(3, sharex=True, sharey=True, gridspec_kw={'hspace': 0}) fig.suptitle('Sharing both axes') axs[0].plot(x, y ** 2) axs[1].plot(x, 0.3 * y, 'o') axs[2].plot(x, y, '+') # Hide x labels and tick labels for all but bottom plot. for ax in axs: ax.label_outer() ############################################################################### # Apart from ``True`` and ``False``, both *sharex* and *sharey* accept the # values 'row' and 'col' to share the values only per row or column. fig, axs = plt.subplots(2, 2, sharex='col', sharey='row', gridspec_kw={'hspace': 0, 'wspace': 0}) (ax1, ax2), (ax3, ax4) = axs fig.suptitle('Sharing x per column, y per row') ax1.plot(x, y) ax2.plot(x, y**2, 'tab:orange') ax3.plot(x + 1, -y, 'tab:green') ax4.plot(x + 2, -y**2, 'tab:red') for ax in axs.flat: ax.label_outer() ############################################################################### # Polar axes # """""""""" # # The parameter *subplot_kw* of `.pyplot.subplots` controls the subplot # properties (see also `.Figure.add_subplot`). In particular, this can be used # to create a grid of polar Axes. fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw=dict(projection='polar')) ax1.plot(x, y) ax2.plot(x, y ** 2) plt.show()
a5e55e420595526bed1a94298d52a82a103e825e60d2d584e6e3a61254857120
""" ================== Basic Subplot Demo ================== Demo with two subplots. For more options, see :doc:`/gallery/subplots_axes_and_figures/subplots_demo` """ import numpy as np import matplotlib.pyplot as plt # Data for plotting x1 = np.linspace(0.0, 5.0) x2 = np.linspace(0.0, 2.0) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) y2 = np.cos(2 * np.pi * x2) # Create two subplots sharing y axis fig, (ax1, ax2) = plt.subplots(2, sharey=True) ax1.plot(x1, y1, 'ko-') ax1.set(title='A tale of 2 subplots', ylabel='Damped oscillation') ax2.plot(x2, y2, 'r.-') ax2.set(xlabel='time (s)', ylabel='Undamped') plt.show()
6c57a00edb3cbb5611a01e86657f5fd10ce49dffd64e071d4dd466cc28ccbf42
""" ====================== Zoom region inset axes ====================== Example of an inset axes and a rectangle showing where the zoom is located. """ import matplotlib.pyplot as plt import numpy as np def get_demo_image(): from matplotlib.cbook import get_sample_data import numpy as np f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 return z, (-3, 4, -4, 3) fig, ax = plt.subplots(figsize=[5, 4]) # make data Z, extent = get_demo_image() Z2 = np.zeros([150, 150], dtype="d") ny, nx = Z.shape Z2[30:30 + ny, 30:30 + nx] = Z ax.imshow(Z2, extent=extent, interpolation="nearest", origin="lower") # inset axes.... axins = ax.inset_axes([0.5, 0.5, 0.47, 0.47]) axins.imshow(Z2, extent=extent, interpolation="nearest", origin="lower") # sub region of the original image x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9 axins.set_xlim(x1, x2) axins.set_ylim(y1, y2) axins.set_xticklabels('') axins.set_yticklabels('') ax.indicate_inset_zoom(axins) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown in this example: import matplotlib matplotlib.axes.Axes.inset_axes matplotlib.axes.Axes.indicate_inset_zoom matplotlib.axes.Axes.imshow
37e277fd327676c7b7063f5b373bbb91d1fcd771e3abb4619438a8dd067074e3
""" =========== Slider Demo =========== Using the slider widget to control visual properties of your plot. In this example, a slider is used to choose the frequency of a sine wave. You can control many continuously-varying properties of your plot in this way. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons fig, ax = plt.subplots() plt.subplots_adjust(left=0.25, bottom=0.25) t = np.arange(0.0, 1.0, 0.001) a0 = 5 f0 = 3 delta_f = 5.0 s = a0 * np.sin(2 * np.pi * f0 * t) l, = plt.plot(t, s, lw=2) plt.axis([0, 1, -10, 10]) axcolor = 'lightgoldenrodyellow' axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor) axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor) sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0, valstep=delta_f) samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0) def update(val): amp = samp.val freq = sfreq.val l.set_ydata(amp*np.sin(2*np.pi*freq*t)) fig.canvas.draw_idle() sfreq.on_changed(update) samp.on_changed(update) resetax = plt.axes([0.8, 0.025, 0.1, 0.04]) button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') def reset(event): sfreq.reset() samp.reset() button.on_clicked(reset) rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor) radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0) def colorfunc(label): l.set_color(label) fig.canvas.draw_idle() radio.on_clicked(colorfunc) plt.show()
aaefd6bd8d5d191eb4dd90562de89bd3a2db9e6dd598a76ae78f3d9e6ad795bd
""" ================== Rectangle Selector ================== Do a mouseclick somewhere, move the mouse to some destination, release the button. This class gives click- and release-events and also draws a line or a box from the click-point to the actual mouseposition (within the same axes) until the button is released. Within the method 'self.ignore()' it is checked whether the button from eventpress and eventrelease are the same. """ from matplotlib.widgets import RectangleSelector import numpy as np import matplotlib.pyplot as plt def line_select_callback(eclick, erelease): 'eclick and erelease are the press and release events' x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2)) print(" The button you used were: %s %s" % (eclick.button, erelease.button)) def toggle_selector(event): print(' Key pressed.') if event.key in ['Q', 'q'] and toggle_selector.RS.active: print(' RectangleSelector deactivated.') toggle_selector.RS.set_active(False) if event.key in ['A', 'a'] and not toggle_selector.RS.active: print(' RectangleSelector activated.') toggle_selector.RS.set_active(True) fig, current_ax = plt.subplots() # make a new plotting range N = 100000 # If N is large one can see x = np.linspace(0.0, 10.0, N) # improvement by use blitting! plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7) # plot something plt.plot(x, +np.cos(.2*np.pi*x), lw=3.5, c='r', alpha=.5) plt.plot(x, -np.sin(.2*np.pi*x), lw=3.5, c='g', alpha=.3) print("\n click --> release") # drawtype is 'box' or 'line' or 'none' toggle_selector.RS = RectangleSelector(current_ax, line_select_callback, drawtype='box', useblit=True, button=[1, 3], # don't use middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True) plt.connect('key_press_event', toggle_selector) plt.show()
16c2fa14094a7de9e84fc18ded5ec8b35a2e6e87171dc3b07d58ea53a95e9ded
""" ============= Check Buttons ============= Turning visual elements on and off with check buttons. This program shows the use of 'Check Buttons' which is similar to check boxes. There are 3 different sine waves shown and we can choose which waves are displayed with the check buttons. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons t = np.arange(0.0, 2.0, 0.01) s0 = np.sin(2*np.pi*t) s1 = np.sin(4*np.pi*t) s2 = np.sin(6*np.pi*t) fig, ax = plt.subplots() l0, = ax.plot(t, s0, visible=False, lw=2, color='k', label='2 Hz') l1, = ax.plot(t, s1, lw=2, color='r', label='4 Hz') l2, = ax.plot(t, s2, lw=2, color='g', label='6 Hz') plt.subplots_adjust(left=0.2) lines = [l0, l1, l2] # Make checkbuttons with all plotted lines with correct visibility rax = plt.axes([0.05, 0.4, 0.1, 0.15]) labels = [str(line.get_label()) for line in lines] visibility = [line.get_visible() for line in lines] check = CheckButtons(rax, labels, visibility) def func(label): index = labels.index(label) lines[index].set_visible(not lines[index].get_visible()) plt.draw() check.on_clicked(func) plt.show()
6f5268b6264d15156e9b4867323710d36481c84bb794c88de7dfda6602acc039
""" =========== Multicursor =========== Showing a cursor on multiple plots simultaneously. This example generates two subplots and on hovering the cursor over data in one subplot, the values of that datapoint are shown in both respectively. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import MultiCursor t = np.arange(0.0, 2.0, 0.01) s1 = np.sin(2*np.pi*t) s2 = np.sin(4*np.pi*t) fig, (ax1, ax2) = plt.subplots(2, sharex=True) ax1.plot(t, s1) ax2.plot(t, s2) multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1) plt.show()
e057ceca3580ad95b5a75cc10c384fd68be548932bd67e8467891f2f3fbee110
""" ===================== Polygon Selector Demo ===================== Shows how one can select indices of a polygon interactively. """ import numpy as np from matplotlib.widgets import PolygonSelector from matplotlib.path import Path class SelectFromCollection(object): """Select indices from a matplotlib collection using `PolygonSelector`. Selected indices are saved in the `ind` attribute. This tool fades out the points that are not part of the selection (i.e., reduces their alpha values). If your collection has alpha < 1, this tool will permanently alter the alpha values. Note that this tool selects collection objects based on their *origins* (i.e., `offsets`). Parameters ---------- ax : :class:`~matplotlib.axes.Axes` Axes to interact with. collection : :class:`matplotlib.collections.Collection` subclass Collection you want to select from. alpha_other : 0 <= float <= 1 To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to `alpha_other`. """ def __init__(self, ax, collection, alpha_other=0.3): self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, (self.Npts, 1)) self.poly = PolygonSelector(ax, self.onselect) self.ind = [] def onselect(self, verts): path = Path(verts) self.ind = np.nonzero(path.contains_points(self.xys))[0] self.fc[:, -1] = self.alpha_other self.fc[self.ind, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() def disconnect(self): self.poly.disconnect_events() self.fc[:, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() if __name__ == '__main__': import matplotlib.pyplot as plt fig, ax = plt.subplots() grid_size = 5 grid_x = np.tile(np.arange(grid_size), grid_size) grid_y = np.repeat(np.arange(grid_size), grid_size) pts = ax.scatter(grid_x, grid_y) selector = SelectFromCollection(ax, pts) print("Select points in the figure by enclosing them within a polygon.") print("Press the 'esc' key to start a new polygon.") print("Try holding the 'shift' key to move all of the vertices.") print("Try holding the 'ctrl' key to move a single vertex.") plt.show() selector.disconnect() # After figure is closed print the coordinates of the selected points print('\nSelected points:') print(selector.xys[selector.ind])
e6082f705277e2116cdd57039108085ea78d254d98c9a1ea50d18c1e7b90e55d
""" =================== Lasso Selector Demo =================== Interactively selecting data points with the lasso tool. This examples plots a scatter plot. You can then select a few points by drawing a lasso loop around the points on the graph. To draw, just click on the graph, hold, and drag it around the points you need to select. """ import numpy as np from matplotlib.widgets import LassoSelector from matplotlib.path import Path class SelectFromCollection(object): """Select indices from a matplotlib collection using `LassoSelector`. Selected indices are saved in the `ind` attribute. This tool fades out the points that are not part of the selection (i.e., reduces their alpha values). If your collection has alpha < 1, this tool will permanently alter the alpha values. Note that this tool selects collection objects based on their *origins* (i.e., `offsets`). Parameters ---------- ax : :class:`~matplotlib.axes.Axes` Axes to interact with. collection : :class:`matplotlib.collections.Collection` subclass Collection you want to select from. alpha_other : 0 <= float <= 1 To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to `alpha_other`. """ def __init__(self, ax, collection, alpha_other=0.3): self.canvas = ax.figure.canvas self.collection = collection self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, (self.Npts, 1)) self.lasso = LassoSelector(ax, onselect=self.onselect) self.ind = [] def onselect(self, verts): path = Path(verts) self.ind = np.nonzero(path.contains_points(self.xys))[0] self.fc[:, -1] = self.alpha_other self.fc[self.ind, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() def disconnect(self): self.lasso.disconnect_events() self.fc[:, -1] = 1 self.collection.set_facecolors(self.fc) self.canvas.draw_idle() if __name__ == '__main__': import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) data = np.random.rand(100, 2) subplot_kw = dict(xlim=(0, 1), ylim=(0, 1), autoscale_on=False) fig, ax = plt.subplots(subplot_kw=subplot_kw) pts = ax.scatter(data[:, 0], data[:, 1], s=80) selector = SelectFromCollection(ax, pts) def accept(event): if event.key == "enter": print("Selected points:") print(selector.xys[selector.ind]) selector.disconnect() ax.set_title("") fig.canvas.draw() fig.canvas.mpl_connect("key_press_event", accept) ax.set_title("Press enter to accept selected points.") plt.show()
5ceb5feeb2f55723ea4dba602ee7d0629d6790605d05befdc93bd2102a570d21
""" ====== Cursor ====== """ from matplotlib.widgets import Cursor import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, facecolor='#FFFFCC') x, y = 4*(np.random.rand(2, 100) - .5) ax.plot(x, y, 'o') ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) # Set useblit=True on most backends for enhanced performance. cursor = Cursor(ax, useblit=True, color='red', linewidth=2) plt.show()
b70b09e46b44d18cbbcabb4b5385a6072b3e3528da6b6611071327ebc152258a
""" ======= Textbox ======= Allowing text input with the Textbox widget. You can use the Textbox widget to let users provide any text that needs to be displayed, including formulas. You can use a submit button to create plots with the given input. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import TextBox fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.2) t = np.arange(-2.0, 2.0, 0.001) s = t ** 2 initial_text = "t ** 2" l, = plt.plot(t, s, lw=2) def submit(text): ydata = eval(text) l.set_ydata(ydata) ax.set_ylim(np.min(ydata), np.max(ydata)) plt.draw() axbox = plt.axes([0.1, 0.05, 0.8, 0.075]) text_box = TextBox(axbox, 'Evaluate', initial=initial_text) text_box.on_submit(submit) plt.show()
d4ea91d26adf24b54faa3b31880a66a1f2c25430555f32a6c7a8acdb8c0b1929
""" ============= Span Selector ============= The SpanSelector is a mouse widget to select a xmin/xmax range and plot the detail view of the selected region in the lower axes """ import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import SpanSelector # Fixing random state for reproducibility np.random.seed(19680801) fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6)) ax1.set(facecolor='#FFFFCC') x = np.arange(0.0, 5.0, 0.01) y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x)) ax1.plot(x, y, '-') ax1.set_ylim(-2, 2) ax1.set_title('Press left mouse button and drag to test') ax2.set(facecolor='#FFFFCC') line2, = ax2.plot(x, y, '-') def onselect(xmin, xmax): indmin, indmax = np.searchsorted(x, (xmin, xmax)) indmax = min(len(x) - 1, indmax) thisx = x[indmin:indmax] thisy = y[indmin:indmax] line2.set_data(thisx, thisy) ax2.set_xlim(thisx[0], thisx[-1]) ax2.set_ylim(thisy.min(), thisy.max()) fig.canvas.draw() # Set useblit=True on most backends for enhanced performance. span = SpanSelector(ax1, onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) plt.show()
f21d8f622f667ef4c0a0dce7c307286888645f7c60e3c365a6c0cb1aa3ded2af
""" ======= Buttons ======= Constructing a simple button GUI to modify a sine wave. The ``next`` and ``previous`` button widget helps visualize the wave with new frequencies. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Button freqs = np.arange(2, 20, 3) fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.2) t = np.arange(0.0, 1.0, 0.001) s = np.sin(2*np.pi*freqs[0]*t) l, = plt.plot(t, s, lw=2) class Index(object): ind = 0 def next(self, event): self.ind += 1 i = self.ind % len(freqs) ydata = np.sin(2*np.pi*freqs[i]*t) l.set_ydata(ydata) plt.draw() def prev(self, event): self.ind -= 1 i = self.ind % len(freqs) ydata = np.sin(2*np.pi*freqs[i]*t) l.set_ydata(ydata) plt.draw() callback = Index() axprev = plt.axes([0.7, 0.05, 0.1, 0.075]) axnext = plt.axes([0.81, 0.05, 0.1, 0.075]) bnext = Button(axnext, 'Next') bnext.on_clicked(callback.next) bprev = Button(axprev, 'Previous') bprev.on_clicked(callback.prev) plt.show()
b14097ba7266e810af26997412b9f68ef7988c582a1ef99e6a04e3cfea4cbe4e
""" ==== Menu ==== """ import numpy as np import matplotlib.colors as colors import matplotlib.patches as patches import matplotlib.mathtext as mathtext import matplotlib.pyplot as plt import matplotlib.artist as artist import matplotlib.image as image class ItemProperties(object): def __init__(self, fontsize=14, labelcolor='black', bgcolor='yellow', alpha=1.0): self.fontsize = fontsize self.labelcolor = labelcolor self.bgcolor = bgcolor self.alpha = alpha self.labelcolor_rgb = colors.to_rgba(labelcolor)[:3] self.bgcolor_rgb = colors.to_rgba(bgcolor)[:3] class MenuItem(artist.Artist): parser = mathtext.MathTextParser("Bitmap") padx = 5 pady = 5 def __init__(self, fig, labelstr, props=None, hoverprops=None, on_select=None): artist.Artist.__init__(self) self.set_figure(fig) self.labelstr = labelstr if props is None: props = ItemProperties() if hoverprops is None: hoverprops = ItemProperties() self.props = props self.hoverprops = hoverprops self.on_select = on_select x, self.depth = self.parser.to_mask( labelstr, fontsize=props.fontsize, dpi=fig.dpi) if props.fontsize != hoverprops.fontsize: raise NotImplementedError( 'support for different font sizes not implemented') self.labelwidth = x.shape[1] self.labelheight = x.shape[0] self.labelArray = np.zeros((x.shape[0], x.shape[1], 4)) self.labelArray[:, :, -1] = x/255. self.label = image.FigureImage(fig, origin='upper') self.label.set_array(self.labelArray) # we'll update these later self.rect = patches.Rectangle((0, 0), 1, 1) self.set_hover_props(False) fig.canvas.mpl_connect('button_release_event', self.check_select) def check_select(self, event): over, junk = self.rect.contains(event) if not over: return if self.on_select is not None: self.on_select(self) def set_extent(self, x, y, w, h): print(x, y, w, h) self.rect.set_x(x) self.rect.set_y(y) self.rect.set_width(w) self.rect.set_height(h) self.label.ox = x + self.padx self.label.oy = y - self.depth + self.pady/2. self.hover = False def draw(self, renderer): self.rect.draw(renderer) self.label.draw(renderer) def set_hover_props(self, b): if b: props = self.hoverprops else: props = self.props r, g, b = props.labelcolor_rgb self.labelArray[:, :, 0] = r self.labelArray[:, :, 1] = g self.labelArray[:, :, 2] = b self.label.set_array(self.labelArray) self.rect.set(facecolor=props.bgcolor, alpha=props.alpha) def set_hover(self, event): 'check the hover status of event and return true if status is changed' b, junk = self.rect.contains(event) changed = (b != self.hover) if changed: self.set_hover_props(b) self.hover = b return changed class Menu(object): def __init__(self, fig, menuitems): self.figure = fig fig.suppressComposite = True self.menuitems = menuitems self.numitems = len(menuitems) maxw = max(item.labelwidth for item in menuitems) maxh = max(item.labelheight for item in menuitems) totalh = self.numitems*maxh + (self.numitems + 1)*2*MenuItem.pady x0 = 100 y0 = 400 width = maxw + 2*MenuItem.padx height = maxh + MenuItem.pady for item in menuitems: left = x0 bottom = y0 - maxh - MenuItem.pady item.set_extent(left, bottom, width, height) fig.artists.append(item) y0 -= maxh + MenuItem.pady fig.canvas.mpl_connect('motion_notify_event', self.on_move) def on_move(self, event): draw = False for item in self.menuitems: draw = item.set_hover(event) if draw: self.figure.canvas.draw() break fig = plt.figure() fig.subplots_adjust(left=0.3) props = ItemProperties(labelcolor='black', bgcolor='yellow', fontsize=15, alpha=0.2) hoverprops = ItemProperties(labelcolor='white', bgcolor='blue', fontsize=15, alpha=0.2) menuitems = [] for label in ('open', 'close', 'save', 'save as', 'quit'): def on_select(item): print('you selected %s' % item.labelstr) item = MenuItem(fig, label, props=props, hoverprops=hoverprops, on_select=on_select) menuitems.append(item) menu = Menu(fig, menuitems) plt.show()
ca01ff01bf9bf0a3830c0380d2a12eef50bd2c62723c0e81bfdecd4f79a2dc4e
""" ============= Radio Buttons ============= Using radio buttons to choose properties of your plot. Radio buttons let you choose between multiple options in a visualization. In this case, the buttons let the user choose one of the three different sine waves to be shown in the plot. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons t = np.arange(0.0, 2.0, 0.01) s0 = np.sin(2*np.pi*t) s1 = np.sin(4*np.pi*t) s2 = np.sin(8*np.pi*t) fig, ax = plt.subplots() l, = ax.plot(t, s0, lw=2, color='red') plt.subplots_adjust(left=0.3) axcolor = 'lightgoldenrodyellow' rax = plt.axes([0.05, 0.7, 0.15, 0.15], facecolor=axcolor) radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz')) def hzfunc(label): hzdict = {'2 Hz': s0, '4 Hz': s1, '8 Hz': s2} ydata = hzdict[label] l.set_ydata(ydata) plt.draw() radio.on_clicked(hzfunc) rax = plt.axes([0.05, 0.4, 0.15, 0.15], facecolor=axcolor) radio2 = RadioButtons(rax, ('red', 'blue', 'green')) def colorfunc(label): l.set_color(label) plt.draw() radio2.on_clicked(colorfunc) rax = plt.axes([0.05, 0.1, 0.15, 0.15], facecolor=axcolor) radio3 = RadioButtons(rax, ('-', '--', '-.', 'steps', ':')) def stylefunc(label): l.set_linestyle(label) plt.draw() radio3.on_clicked(stylefunc) plt.show()
696cedea5ea0607d00097a63ac459629b45efeb10ee4695ecc70c616ce1e6f3d
""" ============== Backend Driver ============== This is used to drive many of the examples across the backends, for regression testing, and comparing backend efficiency. You can specify the backends to be tested either via the --backends switch, which takes a comma-separated list, or as separate arguments, e.g. python backend_driver.py agg ps would test the agg and ps backends. If no arguments are given, a default list of backends will be tested. Interspersed with the backend arguments can be switches for the Python interpreter executing the tests. If entering such arguments causes an option parsing error with the driver script, separate them from driver switches with a --. """ import os import time import sys import glob from optparse import OptionParser import matplotlib.rcsetup as rcsetup from matplotlib.cbook import Bunch, dedent all_backends = list(rcsetup.all_backends) # to leave the original list alone # actual physical directory for each dir dirs = dict(files=os.path.join('..', 'lines_bars_and_markers'), shapes=os.path.join('..', 'shapes_and_collections'), images=os.path.join('..', 'images_contours_and_fields'), pie=os.path.join('..', 'pie_and_polar_charts'), text=os.path.join('..', 'text_labels_and_annotations'), ticks=os.path.join('..', 'ticks_and_spines'), subplots=os.path.join('..', 'subplots_axes_and_figures'), specialty=os.path.join('..', 'specialty_plots'), showcase=os.path.join('..', 'showcase'), pylab=os.path.join('..', 'pylab_examples'), api=os.path.join('..', 'api'), units=os.path.join('..', 'units'), mplot3d=os.path.join('..', 'mplot3d'), colors=os.path.join('..', 'color')) # files in each dir files = dict() files['lines'] = [ 'barh.py', 'cohere.py', 'fill.py', 'fill_demo_features.py', 'line_demo_dash_control.py', 'line_styles_reference.py', 'scatter_with_legend.py' ] files['shapes'] = [ 'path_patch_demo.py', 'scatter_demo.py', ] files['colors'] = [ 'color_cycle_default.py', 'color_cycle_demo.py', ] files['images'] = [ 'image_demo.py', 'contourf_log.py', ] files['statistics'] = [ 'errorbar.py', 'errorbar_features.py', 'histogram_cumulative.py', 'histogram_features.py', 'histogram_histtypes.py', 'histogram_multihist.py', ] files['pie'] = [ 'pie_demo.py', 'polar_bar.py', 'polar_scatter.py', ] files['text_labels_and_annotations'] = [ 'accented_text.py', 'text_demo_fontdict.py', 'text_rotation.py', 'unicode_demo.py', ] files['ticks_and_spines'] = [ 'spines_demo_bounds.py', 'ticklabels_demo_rotation.py', ] files['subplots_axes_and_figures'] = [ 'subplot_demo.py', ] files['showcase'] = [ 'integral_demo.py', ] files['pylab'] = [ 'alignment_test.py', 'annotation_demo.py', 'annotation_demo.py', 'annotation_demo2.py', 'annotation_demo2.py', 'anscombe.py', 'arctest.py', 'arrow_demo.py', 'axes_demo.py', 'axes_props.py', 'axhspan_demo.py', 'axis_equal_demo.py', 'bar_stacked.py', 'barb_demo.py', 'barchart_demo.py', 'barcode_demo.py', 'boxplot_demo.py', 'broken_barh.py', 'color_by_yvalue.py', 'color_demo.py', 'colorbar_tick_labelling_demo.py', 'contour_demo.py', 'contour_image.py', 'contour_label_demo.py', 'contourf_demo.py', 'coords_demo.py', 'coords_report.py', 'csd_demo.py', 'cursor_demo.py', 'custom_cmap.py', 'custom_figure_class.py', 'custom_ticker1.py', 'customize_rc.py', 'dashpointlabel.py', 'date_demo_convert.py', 'date_demo_rrule.py', 'date_index_formatter.py', 'dolphin.py', 'ellipse_collection.py', 'ellipse_demo.py', 'ellipse_rotated.py', 'errorbar_limits.py', 'fancyarrow_demo.py', 'fancybox_demo.py', 'fancybox_demo2.py', 'fancytextbox_demo.py', 'figimage_demo.py', 'figlegend_demo.py', 'figure_title.py', 'fill_between_demo.py', 'fill_spiral.py', 'findobj_demo.py', 'fonts_demo.py', 'fonts_demo_kw.py', 'ganged_plots.py', 'geo_demo.py', 'gradient_bar.py', 'griddata_demo.py', 'hatch_demo.py', 'hexbin_demo.py', 'hexbin_demo2.py', 'vline_hline_demo.py', 'image_clip_path.py', 'image_demo.py', 'image_demo2.py', 'image_interp.py', 'image_masked.py', 'image_nonuniform.py', 'image_origin.py', 'image_slices_viewer.py', 'interp_demo.py', 'invert_axes.py', 'layer_images.py', 'legend_demo2.py', 'legend_demo3.py', 'line_collection.py', 'line_collection2.py', 'log_bar.py', 'log_demo.py', 'log_test.py', 'major_minor_demo1.py', 'major_minor_demo2.py', 'masked_demo.py', 'mathtext_demo.py', 'mathtext_examples.py', 'matshow.py', 'mri_demo.py', 'mri_with_eeg.py', 'multi_image.py', 'multiline.py', 'multiple_figs_demo.py', 'nan_test.py', 'scalarformatter.py', 'pcolor_demo.py', 'pcolor_log.py', 'pcolor_small.py', 'pie_demo2.py', 'plotfile_demo.py', 'polar_demo.py', 'polar_legend.py', 'psd_demo.py', 'psd_demo2.py', 'psd_demo3.py', 'quadmesh_demo.py', 'quiver_demo.py', 'scatter_custom_symbol.py', 'scatter_demo2.py', 'scatter_masked.py', 'scatter_profile.py', 'scatter_star_poly.py', #'set_and_get.py', 'shared_axis_across_figures.py', 'shared_axis_demo.py', 'simple_plot.py', 'specgram_demo.py', 'spine_placement_demo.py', 'spy_demos.py', 'stem_plot.py', 'step_demo.py', 'stix_fonts_demo.py', 'subplots_adjust.py', 'symlog_demo.py', 'table_demo.py', 'text_rotation_relative_to_line.py', 'transoffset.py', 'xcorr_demo.py', 'zorder_demo.py', ] files['api'] = [ 'agg_oo.py', 'barchart_demo.py', 'bbox_intersect.py', 'collections_demo.py', 'colorbar_only.py', 'custom_projection_example.py', 'custom_scale_example.py', 'date_demo.py', 'date_index_formatter.py', 'donut_demo.py', 'font_family_rc.py', 'image_zcoord.py', 'joinstyle.py', 'legend_demo.py', 'line_with_text.py', 'logo2.py', 'mathtext_asarray.py', 'patch_collection.py', 'quad_bezier.py', 'scatter_piecharts.py', 'span_regions.py', 'two_scales.py', 'unicode_minus.py', 'watermark_image.py', 'watermark_text.py', ] files['units'] = [ 'annotate_with_units.py', #'artist_tests.py', # broken, fixme 'bar_demo2.py', #'bar_unit_demo.py', # broken, fixme #'ellipse_with_units.py', # broken, fixme 'radian_demo.py', 'units_sample.py', #'units_scatter.py', # broken, fixme ] files['mplot3d'] = [ '2dcollections3d_demo.py', 'bars3d_demo.py', 'contour3d_demo.py', 'contour3d_demo2.py', 'contourf3d_demo.py', 'lines3d_demo.py', 'polys3d_demo.py', 'scatter3d_demo.py', 'surface3d_demo.py', 'surface3d_demo2.py', 'text3d_demo.py', 'wire3d_demo.py', ] # dict from dir to files we know we don't want to test (e.g., examples # not using pyplot, examples requiring user input, animation examples, # examples that may only work in certain environs (usetex examples?), # examples that generate multiple figures excluded = { 'units': ['__init__.py', 'date_support.py', ], } def report_missing(dir, flist): 'report the py files in dir that are not in flist' globstr = os.path.join(dir, '*.py') fnames = glob.glob(globstr) pyfiles = {os.path.split(fullpath)[-1] for fullpath in fnames} exclude = set(excluded.get(dir, [])) flist = set(flist) missing = list(pyfiles - flist - exclude) if missing: print('%s files not tested: %s' % (dir, ', '.join(sorted(missing)))) def report_all_missing(directories): for f in directories: report_missing(dirs[f], files[f]) # tests known to fail on a given backend failbackend = dict( svg=('tex_demo.py', ), agg=('hyperlinks.py', ), pdf=('hyperlinks.py', ), ps=('hyperlinks.py', ), ) import subprocess def run(arglist): try: ret = subprocess.call(arglist) except KeyboardInterrupt: sys.exit() else: return ret def drive(backend, directories, python=['python'], switches=[]): exclude = failbackend.get(backend, []) # Clear the destination directory for the examples path = backend if os.path.exists(path): for fname in os.listdir(path): os.unlink(os.path.join(path, fname)) else: os.mkdir(backend) failures = [] testcases = [os.path.join(dirs[d], fname) for d in directories for fname in files[d]] for fullpath in testcases: print('\tdriving %-40s' % (fullpath)) sys.stdout.flush() fpath, fname = os.path.split(fullpath) if fname in exclude: print('\tSkipping %s, known to fail on backend: %s' % backend) continue basename, ext = os.path.splitext(fname) outfile = os.path.join(path, basename) tmpfile_name = '_tmp_%s.py' % basename tmpfile = open(tmpfile_name, 'w') for line in open(fullpath): line_lstrip = line.lstrip() if line_lstrip.startswith("#"): tmpfile.write(line) tmpfile.writelines(( 'import sys\n', 'sys.path.append("%s")\n' % fpath.replace('\\', '\\\\'), 'import matplotlib\n', 'matplotlib.use("%s")\n' % backend, 'from pylab import savefig\n', 'import numpy\n', 'numpy.seterr(invalid="ignore")\n', )) for line in open(fullpath): if line.lstrip().startswith(('matplotlib.use', 'savefig', 'show')): continue tmpfile.write(line) if backend in rcsetup.interactive_bk: tmpfile.write('show()') else: tmpfile.write('\nsavefig(r"%s", dpi=150)' % outfile) tmpfile.close() start_time = time.time() program = [x % {'name': basename} for x in python] ret = run(program + [tmpfile_name] + switches) end_time = time.time() print("%s %s" % ((end_time - start_time), ret)) # subprocess.call([python, tmpfile_name] + switches) os.remove(tmpfile_name) if ret: failures.append(fullpath) return failures def parse_options(): doc = __doc__.split("\n\n") if __doc__ else " " op = OptionParser(description=doc[0].strip(), usage='%prog [options] [--] [backends and switches]', #epilog='\n'.join(doc[1:]) # epilog not supported on my python2.4 machine: JDH ) op.disable_interspersed_args() op.set_defaults(dirs='pylab,api,units,mplot3d', clean=False, coverage=False, valgrind=False) op.add_option('-d', '--dirs', '--directories', type='string', dest='dirs', help=dedent(''' Run only the tests in these directories; comma-separated list of one or more of: pylab (or pylab_examples), api, units, mplot3d''')) op.add_option('-b', '--backends', type='string', dest='backends', help=dedent(''' Run tests only for these backends; comma-separated list of one or more of: agg, ps, svg, pdf, template, cairo, Default is everything except cairo.''')) op.add_option('--clean', action='store_true', dest='clean', help='Remove result directories, run no tests') op.add_option('-c', '--coverage', action='store_true', dest='coverage', help='Run in coverage.py') op.add_option('-v', '--valgrind', action='store_true', dest='valgrind', help='Run in valgrind') options, args = op.parse_args() switches = [x for x in args if x.startswith('--')] backends = [x.lower() for x in args if not x.startswith('--')] if options.backends: backends += [be.lower() for be in options.backends.split(',')] result = Bunch( dirs=options.dirs.split(','), backends=backends or ['agg', 'ps', 'svg', 'pdf', 'template'], clean=options.clean, coverage=options.coverage, valgrind=options.valgrind, switches=switches) if 'pylab_examples' in result.dirs: result.dirs[result.dirs.index('pylab_examples')] = 'pylab' return result if __name__ == '__main__': times = {} failures = {} options = parse_options() if options.clean: localdirs = [d for d in glob.glob('*') if os.path.isdir(d)] all_backends_set = set(all_backends) for d in localdirs: if d.lower() not in all_backends_set: continue print('removing %s' % d) for fname in glob.glob(os.path.join(d, '*')): os.remove(fname) os.rmdir(d) for fname in glob.glob('_tmp*.py'): os.remove(fname) print('all clean...') raise SystemExit if options.coverage: python = ['coverage.py', '-x'] elif options.valgrind: python = ['valgrind', '--tool=memcheck', '--leak-check=yes', '--log-file=%(name)s', sys.executable] elif sys.platform == 'win32': python = [sys.executable] else: python = [sys.executable] report_all_missing(options.dirs) for backend in options.backends: print('testing %s %s' % (backend, ' '.join(options.switches))) t0 = time.time() failures[backend] = \ drive(backend, options.dirs, python, options.switches) t1 = time.time() times[backend] = (t1 - t0) / 60 for backend, elapsed in times.items(): print('Backend %s took %1.2f minutes to complete' % (backend, elapsed)) failed = failures[backend] if failed: print(' Failures: %s' % failed) if 'template' in times: print('\ttemplate ratio %1.3f, template residual %1.3f' % ( elapsed/times['template'], elapsed - times['template']))
fb5bbf5bb039716a3c1935a04b686c958b2d3e73e57fff6af725af8abb55ec19
""" ============ Scatter plot ============ This example showcases a simple scatter plot. """ import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = (30 * np.random.rand(N))**2 # 0 to 15 point radii plt.scatter(x, y, s=area, c=colors, alpha=0.5) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown in this example: import matplotlib matplotlib.axes.Axes.scatter matplotlib.pyplot.scatter
563d267ea1007bbb5f134ae92de02d257f48479db7a50138b9f3a9ada141fe93
""" ============ Bezier Curve ============ This example showcases the `~.patches.PathPatch` object to create a Bezier polycurve path patch. """ import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt Path = mpath.Path fig, ax = plt.subplots() pp1 = mpatches.PathPatch( Path([(0, 0), (1, 0), (1, 1), (0, 0)], [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]), fc="none", transform=ax.transData) ax.add_patch(pp1) ax.plot([0.75], [0.25], "ro") ax.set_title('The red point should be on the path') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.path matplotlib.path.Path matplotlib.patches matplotlib.patches.PathPatch matplotlib.axes.Axes.add_patch
0cf3d47f4a0884b11b265e91080c076ddd167e1c96deb284e6e95f1f8ac1c823
''' ========================================================= Line, Poly and RegularPoly Collection with autoscaling ========================================================= For the first two subplots, we will use spirals. Their size will be set in plot units, not data units. Their positions will be set in data units by using the "offsets" and "transOffset" kwargs of the `~.collections.LineCollection` and `~.collections.PolyCollection`. The third subplot will make regular polygons, with the same type of scaling and positioning as in the first two. The last subplot illustrates the use of "offsets=(xo,yo)", that is, a single tuple instead of a list of tuples, to generate successively offset curves, with the offset given in data units. This behavior is available only for the LineCollection. ''' import matplotlib.pyplot as plt from matplotlib import collections, colors, transforms import numpy as np nverts = 50 npts = 100 # Make some spirals r = np.arange(nverts) theta = np.linspace(0, 2*np.pi, nverts) xx = r * np.sin(theta) yy = r * np.cos(theta) spiral = np.column_stack([xx, yy]) # Fixing random state for reproducibility rs = np.random.RandomState(19680801) # Make some offsets xyo = rs.randn(npts, 2) # Make a list of colors cycling through the default series. colors = [colors.to_rgba(c) for c in plt.rcParams['axes.prop_cycle'].by_key()['color']] fig, axes = plt.subplots(2, 2) fig.subplots_adjust(top=0.92, left=0.07, right=0.97, hspace=0.3, wspace=0.3) ((ax1, ax2), (ax3, ax4)) = axes # unpack the axes col = collections.LineCollection([spiral], offsets=xyo, transOffset=ax1.transData) trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0/72.0) col.set_transform(trans) # the points to pixels transform # Note: the first argument to the collection initializer # must be a list of sequences of x,y tuples; we have only # one sequence, but we still have to put it in a list. ax1.add_collection(col, autolim=True) # autolim=True enables autoscaling. For collections with # offsets like this, it is neither efficient nor accurate, # but it is good enough to generate a plot that you can use # as a starting point. If you know beforehand the range of # x and y that you want to show, it is better to set them # explicitly, leave out the autolim kwarg (or set it to False), # and omit the 'ax1.autoscale_view()' call below. # Make a transform for the line segments such that their size is # given in points: col.set_color(colors) ax1.autoscale_view() # See comment above, after ax1.add_collection. ax1.set_title('LineCollection using offsets') # The same data as above, but fill the curves. col = collections.PolyCollection([spiral], offsets=xyo, transOffset=ax2.transData) trans = transforms.Affine2D().scale(fig.dpi/72.0) col.set_transform(trans) # the points to pixels transform ax2.add_collection(col, autolim=True) col.set_color(colors) ax2.autoscale_view() ax2.set_title('PolyCollection using offsets') # 7-sided regular polygons col = collections.RegularPolyCollection( 7, sizes=np.abs(xx) * 10.0, offsets=xyo, transOffset=ax3.transData) trans = transforms.Affine2D().scale(fig.dpi / 72.0) col.set_transform(trans) # the points to pixels transform ax3.add_collection(col, autolim=True) col.set_color(colors) ax3.autoscale_view() ax3.set_title('RegularPolyCollection using offsets') # Simulate a series of ocean current profiles, successively # offset by 0.1 m/s so that they form what is sometimes called # a "waterfall" plot or a "stagger" plot. nverts = 60 ncurves = 20 offs = (0.1, 0.0) yy = np.linspace(0, 2*np.pi, nverts) ym = np.max(yy) xx = (0.2 + (ym - yy) / ym) ** 2 * np.cos(yy - 0.4) * 0.5 segs = [] for i in range(ncurves): xxx = xx + 0.02*rs.randn(nverts) curve = np.column_stack([xxx, yy * 100]) segs.append(curve) col = collections.LineCollection(segs, offsets=offs) ax4.add_collection(col, autolim=True) col.set_color(colors) ax4.autoscale_view() ax4.set_title('Successive data offsets') ax4.set_xlabel('Zonal velocity component (m/s)') ax4.set_ylabel('Depth (m)') # Reverse the y-axis so depth increases downward ax4.set_ylim(ax4.get_ylim()[::-1]) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.figure.Figure matplotlib.collections matplotlib.collections.LineCollection matplotlib.collections.RegularPolyCollection matplotlib.axes.Axes.add_collection matplotlib.axes.Axes.autoscale_view matplotlib.transforms.Affine2D matplotlib.transforms.Affine2D.scale
7f0a446e85241f3070736a4a6d22f06cd4a587181da9532c7c3810adf93bf19f
""" ============= Compound path ============= Make a compound path -- in this case two simple polygons, a rectangle and a triangle. Use ``CLOSEPOLY`` and ``MOVETO`` for the different parts of the compound path """ import numpy as np from matplotlib.path import Path from matplotlib.patches import PathPatch import matplotlib.pyplot as plt vertices = [] codes = [] codes = [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY] vertices = [(1, 1), (1, 2), (2, 2), (2, 1), (0, 0)] codes += [Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY] vertices += [(4, 4), (5, 5), (5, 4), (0, 0)] vertices = np.array(vertices, float) path = Path(vertices, codes) pathpatch = PathPatch(path, facecolor='None', edgecolor='green') fig, ax = plt.subplots() ax.add_patch(pathpatch) ax.set_title('A compound path') ax.autoscale_view() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.path matplotlib.path.Path matplotlib.patches matplotlib.patches.PathPatch matplotlib.axes.Axes.add_patch matplotlib.axes.Axes.autoscale_view
8c9ca2ddc2f5ce10bad57764fe26af7a8746c36593570f93b5880928a78949f6
""" ============================ Circles, Wedges and Polygons ============================ This example demonstrates how to use :class:`patch collections<~.collections.PatchCollection>`. """ import numpy as np from matplotlib.patches import Circle, Wedge, Polygon from matplotlib.collections import PatchCollection import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots() resolution = 50 # the number of vertices N = 3 x = np.random.rand(N) y = np.random.rand(N) radii = 0.1*np.random.rand(N) patches = [] for x1, y1, r in zip(x, y, radii): circle = Circle((x1, y1), r) patches.append(circle) x = np.random.rand(N) y = np.random.rand(N) radii = 0.1*np.random.rand(N) theta1 = 360.0*np.random.rand(N) theta2 = 360.0*np.random.rand(N) for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2): wedge = Wedge((x1, y1), r, t1, t2) patches.append(wedge) # Some limiting conditions on Wedge patches += [ Wedge((.3, .7), .1, 0, 360), # Full circle Wedge((.7, .8), .2, 0, 360, width=0.05), # Full ring Wedge((.8, .3), .2, 0, 45), # Full sector Wedge((.8, .3), .2, 45, 90, width=0.10), # Ring sector ] for i in range(N): polygon = Polygon(np.random.rand(N, 2), True) patches.append(polygon) colors = 100*np.random.rand(len(patches)) p = PatchCollection(patches, alpha=0.4) p.set_array(np.array(colors)) ax.add_collection(p) fig.colorbar(p, ax=ax) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.patches matplotlib.patches.Circle matplotlib.patches.Wedge matplotlib.patches.Polygon matplotlib.collections.PatchCollection matplotlib.collections.Collection.set_array matplotlib.axes.Axes.add_collection matplotlib.figure.Figure.colorbar
352a330854e6c036f74122c51a777dace55701ab97be44549e7fea6519f93851
""" ======== Dolphins ======== This example shows how to draw, and manipulate shapes given vertices and nodes using the `~.path.Path`, `~.patches.PathPatch` and `~matplotlib.transforms` classes. """ import matplotlib.cm as cm import matplotlib.pyplot as plt from matplotlib.patches import Circle, PathPatch from matplotlib.path import Path from matplotlib.transforms import Affine2D import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) r = np.random.rand(50) t = np.random.rand(50) * np.pi * 2.0 x = r * np.cos(t) y = r * np.sin(t) fig, ax = plt.subplots(figsize=(6, 6)) circle = Circle((0, 0), 1, facecolor='none', edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5) ax.add_patch(circle) im = plt.imshow(np.random.random((100, 100)), origin='lower', cmap=cm.winter, interpolation='spline36', extent=([-1, 1, -1, 1])) im.set_clip_path(circle) plt.plot(x, y, 'o', color=(0.9, 0.9, 1.0), alpha=0.8) # Dolphin from OpenClipart library by Andy Fitzsimon # <cc:License rdf:about="http://web.resource.org/cc/PublicDomain"> # <cc:permits rdf:resource="http://web.resource.org/cc/Reproduction"/> # <cc:permits rdf:resource="http://web.resource.org/cc/Distribution"/> # <cc:permits rdf:resource="http://web.resource.org/cc/DerivativeWorks"/> # </cc:License> dolphin = """ M -0.59739425,160.18173 C -0.62740401,160.18885 -0.57867129,160.11183 -0.57867129,160.11183 C -0.57867129,160.11183 -0.5438361,159.89315 -0.39514638,159.81496 C -0.24645668,159.73678 -0.18316813,159.71981 -0.18316813,159.71981 C -0.18316813,159.71981 -0.10322971,159.58124 -0.057804323,159.58725 C -0.029723983,159.58913 -0.061841603,159.60356 -0.071265813,159.62815 C -0.080250183,159.65325 -0.082918513,159.70554 -0.061841203,159.71248 C -0.040763903,159.7194 -0.0066711426,159.71091 0.077336307,159.73612 C 0.16879567,159.76377 0.28380306,159.86448 0.31516668,159.91533 C 0.3465303,159.96618 0.5011127,160.1771 0.5011127,160.1771 C 0.63668998,160.19238 0.67763022,160.31259 0.66556395,160.32668 C 0.65339985,160.34212 0.66350443,160.33642 0.64907098,160.33088 C 0.63463742,160.32533 0.61309688,160.297 0.5789627,160.29339 C 0.54348657,160.28968 0.52329693,160.27674 0.50728856,160.27737 C 0.49060916,160.27795 0.48965803,160.31565 0.46114204,160.33673 C 0.43329696,160.35786 0.4570711,160.39871 0.43309565,160.40685 C 0.4105108,160.41442 0.39416631,160.33027 0.3954995,160.2935 C 0.39683269,160.25672 0.43807996,160.21522 0.44567915,160.19734 C 0.45327833,160.17946 0.27946869,159.9424 -0.061852613,159.99845 C -0.083965233,160.0427 -0.26176109,160.06683 -0.26176109,160.06683 C -0.30127962,160.07028 -0.21167141,160.09731 -0.24649368,160.1011 C -0.32642366,160.11569 -0.34521187,160.06895 -0.40622293,160.0819 C -0.467234,160.09485 -0.56738444,160.17461 -0.59739425,160.18173 """ vertices = [] codes = [] parts = dolphin.split() i = 0 code_map = { 'M': (Path.MOVETO, 1), 'C': (Path.CURVE4, 3), 'L': (Path.LINETO, 1)} while i < len(parts): code = parts[i] path_code, npoints = code_map[code] codes.extend([path_code] * npoints) vertices.extend([[float(x) for x in y.split(',')] for y in parts[i + 1:i + npoints + 1]]) i += npoints + 1 vertices = np.array(vertices, float) vertices[:, 1] -= 160 dolphin_path = Path(vertices, codes) dolphin_patch = PathPatch(dolphin_path, facecolor=(0.6, 0.6, 0.6), edgecolor=(0.0, 0.0, 0.0)) ax.add_patch(dolphin_patch) vertices = Affine2D().rotate_deg(60).transform(vertices) dolphin_path2 = Path(vertices, codes) dolphin_patch2 = PathPatch(dolphin_path2, facecolor=(0.5, 0.5, 0.5), edgecolor=(0.0, 0.0, 0.0)) ax.add_patch(dolphin_patch2) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.path matplotlib.path.Path matplotlib.patches matplotlib.patches.PathPatch matplotlib.patches.Circle matplotlib.axes.Axes.add_patch matplotlib.transforms matplotlib.transforms.Affine2D matplotlib.transforms.Affine2D.rotate_deg
b9a7f9c6e5a75458383219abe314e00278416d646ca11aaaa68dff138001697b
""" =========== Marker Path =========== Using a `~.path.Path` as marker for a `~.axes.Axes.plot`. """ import matplotlib.pyplot as plt import matplotlib.path as mpath import numpy as np star = mpath.Path.unit_regular_star(6) circle = mpath.Path.unit_circle() # concatenate the circle with an internal cutout of the star verts = np.concatenate([circle.vertices, star.vertices[::-1, ...]]) codes = np.concatenate([circle.codes, star.codes]) cut_star = mpath.Path(verts, codes) plt.plot(np.arange(10)**2, '--r', marker=cut_star, markersize=15) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.path matplotlib.path.Path matplotlib.path.Path.unit_regular_star matplotlib.path.Path.unit_circle matplotlib.axes.Axes.plot matplotlib.pyplot.plot
f9f9eec6fdf87b17d2b6f49dcff6bc75a0e554b4c5ca2015696fef9e47829057
""" ================== Ellipse Collection ================== Drawing a collection of ellipses. While this would equally be possible using a `~.collections.EllipseCollection` or `~.collections.PathCollection`, the use of an `~.collections.EllipseCollection` allows for much shorter code. """ 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.column_stack((X.ravel(), Y.ravel())) ww = X / 10.0 hh = Y / 15.0 aa = X * 9 fig, ax = plt.subplots() 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() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.collections matplotlib.collections.EllipseCollection matplotlib.axes.Axes.add_collection matplotlib.axes.Axes.autoscale_view matplotlib.cm.ScalarMappable.set_array
6ac53952da34b97115827136a59ede45549f67f7e122e5fd130694580c5be5a4
""" =============== Line Collection =============== Plotting lines with Matplotlib. :class:`~matplotlib.collections.LineCollection` allows one to plot multiple lines on a figure. Below we show off some of its properties. """ import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib import colors as mcolors import numpy as np # In order to efficiently plot many lines in a single set of axes, # Matplotlib has the ability to add the lines all at once. Here is a # simple example showing how it is done. x = np.arange(100) # Here are many sets of y to plot vs x ys = x[:50, np.newaxis] + x[np.newaxis, :] segs = np.zeros((50, 100, 2)) segs[:, :, 1] = ys segs[:, :, 0] = x # Mask some values to test masked array support: segs = np.ma.masked_where((segs > 50) & (segs < 60), segs) # We need to set the plot limits. fig, ax = plt.subplots() ax.set_xlim(x.min(), x.max()) ax.set_ylim(ys.min(), ys.max()) # colors is sequence of rgba tuples # linestyle is a string or dash tuple. Legal string values are # solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) # where onoffseq is an even length tuple of on and off ink in points. # If linestyle is omitted, 'solid' is used # See :class:`matplotlib.collections.LineCollection` for more information colors = [mcolors.to_rgba(c) for c in plt.rcParams['axes.prop_cycle'].by_key()['color']] line_segments = LineCollection(segs, linewidths=(0.5, 1, 1.5, 2), colors=colors, linestyle='solid') ax.add_collection(line_segments) ax.set_title('Line collection with masked arrays') plt.show() ############################################################################### # In order to efficiently plot many lines in a single set of axes, # Matplotlib has the ability to add the lines all at once. Here is a # simple example showing how it is done. N = 50 x = np.arange(N) # Here are many sets of y to plot vs x ys = [x + i for i in x] # We need to set the plot limits, they will not autoscale fig, ax = plt.subplots() ax.set_xlim(np.min(x), np.max(x)) ax.set_ylim(np.min(ys), np.max(ys)) # colors is sequence of rgba tuples # linestyle is a string or dash tuple. Legal string values are # solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) # where onoffseq is an even length tuple of on and off ink in points. # If linestyle is omitted, 'solid' is used # See :class:`matplotlib.collections.LineCollection` for more information # Make a sequence of x,y pairs line_segments = LineCollection([np.column_stack([x, y]) for y in ys], linewidths=(0.5, 1, 1.5, 2), linestyles='solid') line_segments.set_array(x) ax.add_collection(line_segments) axcb = fig.colorbar(line_segments) axcb.set_label('Line Number') ax.set_title('Line Collection with mapped colors') plt.sci(line_segments) # This allows interactive changing of the colormap. plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.collections matplotlib.collections.LineCollection matplotlib.cm.ScalarMappable.set_array matplotlib.axes.Axes.add_collection matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.pyplot.sci
d88a7891dff9df656430a9aac1ce78b200c287c0523d991591fc9039eb7bc79e
r""" ================ PathPatch object ================ This example shows how to create `~.path.Path` and `~.patches.PathPatch` objects through Matplotlib's API. """ import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt fig, ax = plt.subplots() Path = mpath.Path path_data = [ (Path.MOVETO, (1.58, -2.57)), (Path.CURVE4, (0.35, -1.1)), (Path.CURVE4, (-1.75, 2.0)), (Path.CURVE4, (0.375, 2.0)), (Path.LINETO, (0.85, 1.15)), (Path.CURVE4, (2.2, 3.2)), (Path.CURVE4, (3, 0.05)), (Path.CURVE4, (2.0, -0.5)), (Path.CLOSEPOLY, (1.58, -2.57)), ] codes, verts = zip(*path_data) path = mpath.Path(verts, codes) patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5) ax.add_patch(patch) # plot control points and connecting lines x, y = zip(*path.vertices) line, = ax.plot(x, y, 'go-') ax.grid() ax.axis('equal') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.path matplotlib.path.Path matplotlib.patches matplotlib.patches.PathPatch matplotlib.axes.Axes.add_patch
461d2d49ee566256fe0e8dd30f293c6683743a30de84b9989db303c9eea27001
""" ========== Hatch Demo ========== Hatching (pattern filled polygons) is supported currently in the PS, PDF, SVG and Agg backends only. """ import matplotlib.pyplot as plt from matplotlib.patches import Ellipse, Polygon fig, (ax1, ax2, ax3) = plt.subplots(3) ax1.bar(range(1, 5), range(1, 5), color='red', edgecolor='black', hatch="/") ax1.bar(range(1, 5), [6] * 4, bottom=range(1, 5), color='blue', edgecolor='black', hatch='//') ax1.set_xticks([1.5, 2.5, 3.5, 4.5]) bars = ax2.bar(range(1, 5), range(1, 5), color='yellow', ecolor='black') + \ ax2.bar(range(1, 5), [6] * 4, bottom=range(1, 5), color='green', ecolor='black') ax2.set_xticks([1.5, 2.5, 3.5, 4.5]) patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.') for bar, pattern in zip(bars, patterns): bar.set_hatch(pattern) ax3.fill([1, 3, 3, 1], [1, 1, 2, 2], fill=False, hatch='\\') ax3.add_patch(Ellipse((4, 1.5), 4, 0.5, fill=False, hatch='*')) ax3.add_patch(Polygon([[0, 0], [4, 1.1], [6, 2.5], [2, 1.4]], closed=True, fill=False, hatch='/')) ax3.set_xlim((0, 6)) ax3.set_ylim((0, 2.5)) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.patches matplotlib.patches.Ellipse matplotlib.patches.Polygon matplotlib.axes.Axes.add_patch matplotlib.patches.Patch.set_hatch matplotlib.axes.Axes.bar matplotlib.pyplot.bar
cc00076aca93843462a1c66ce60d69504f059cb7ff1e80e8caeae8942c289a70
""" ============ Ellipse Demo ============ Draw many ellipses. Here individual ellipses are drawn. Compare this to the :doc:`Ellipse collection example </gallery/shapes_and_collections/ellipse_collection>`. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Ellipse NUM = 250 ells = [Ellipse(xy=np.random.rand(2) * 10, width=np.random.rand(), height=np.random.rand(), angle=np.random.rand() * 360) for i in range(NUM)] fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'}) for e in ells: ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_alpha(np.random.rand()) e.set_facecolor(np.random.rand(3)) ax.set_xlim(0, 10) ax.set_ylim(0, 10) plt.show() ############################################################################# # =============== # Ellipse Rotated # =============== # # Draw many ellipses with different angles. # import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Ellipse delta = 45.0 # degrees angles = np.arange(0, 360 + delta, delta) ells = [Ellipse((1, 1), 4, 2, a) for a in angles] a = plt.subplot(111, aspect='equal') for e in ells: e.set_clip_box(a.bbox) e.set_alpha(0.1) a.add_artist(e) plt.xlim(-2, 4) plt.ylim(-1, 3) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.patches matplotlib.patches.Ellipse matplotlib.axes.Axes.add_artist matplotlib.artist.Artist.set_clip_box matplotlib.artist.Artist.set_alpha matplotlib.patches.Patch.set_facecolor
34e274109dee7e98ce92d4404fc4d6598b72f1e9fe27763d965699fa26700987
""" =========== Arrow guide =========== Adding arrow patches to plots. Arrows are often used to annotate plots. This tutorial shows how to plot arrows that behave differently when the data limits on a plot are changed. In general, points on a plot can either be fixed in "data space" or "display space". Something plotted in data space moves when the data limits are altered - an example would the points in a scatter plot. Something plotted in display space stays static when data limits are altered - an example would be a figure title or the axis labels. Arrows consist of a head (and possibly a tail) and a stem drawn between a start point and end point, called 'anchor points' from now on. Here we show three use cases for plotting arrows, depending on whether the head or anchor points need to be fixed in data or display space: 1. Head shape fixed in display space, anchor points fixed in data space 2. Head shape and anchor points fixed in display space 3. Entire patch fixed in data space Below each use case is presented in turn. """ import matplotlib.patches as mpatches import matplotlib.pyplot as plt x_tail = 0.1 y_tail = 0.1 x_head = 0.9 y_head = 0.9 dx = x_head - x_tail dy = y_head - y_tail ############################################################################### # Head shape fixed in display space and anchor points fixed in data space # ----------------------------------------------------------------------- # # This is useful if you are annotating a plot, and don't want the arrow to # to change shape or position if you pan or scale the plot. Note that when # the axis limits change # # In this case we use `.patches.FancyArrowPatch` # # Note that when the axis limits are changed, the arrow shape stays the same, # but the anchor points move. fig, axs = plt.subplots(nrows=2) arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy), mutation_scale=100) axs[0].add_patch(arrow) arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy), mutation_scale=100) axs[1].add_patch(arrow) axs[1].set_xlim(0, 2) axs[1].set_ylim(0, 2) ############################################################################### # Head shape and anchor points fixed in display space # --------------------------------------------------- # # This is useful if you are annotating a plot, and don't want the arrow to # to change shape or position if you pan or scale the plot. # # In this case we use `.patches.FancyArrowPatch`, and pass the keyword argument # ``transform=ax.transAxes`` where ``ax`` is the axes we are adding the patch # to. # # Note that when the axis limits are changed, the arrow shape and location # stays the same. fig, axs = plt.subplots(nrows=2) arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy), mutation_scale=100, transform=axs[0].transAxes) axs[0].add_patch(arrow) arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy), mutation_scale=100, transform=axs[1].transAxes) axs[1].add_patch(arrow) axs[1].set_xlim(0, 2) axs[1].set_ylim(0, 2) ############################################################################### # Head shape and anchor points fixed in data space # ------------------------------------------------ # # In this case we use `.patches.Arrow` # # Note that when the axis limits are changed, the arrow shape and location # changes. fig, axs = plt.subplots(nrows=2) arrow = mpatches.Arrow(x_tail, y_tail, dx, dy) axs[0].add_patch(arrow) arrow = mpatches.Arrow(x_tail, y_tail, dx, dy) axs[1].add_patch(arrow) axs[1].set_xlim(0, 2) axs[1].set_ylim(0, 2) ############################################################################### plt.show()
8ddde47890b087090e9c0160eafabb57e98e727c5f4c631595ace1a02058a7f6
""" ================================ Reference for Matplotlib artists ================================ This example displays several of Matplotlib's graphics primitives (artists) drawn using matplotlib API. A full list of artists and the documentation is available at :ref:`the artist API <artist-api>`. Copyright (c) 2010, Bartosz Telenczuk BSD License """ import matplotlib.pyplot as plt import numpy as np import matplotlib.path as mpath import matplotlib.lines as mlines import matplotlib.patches as mpatches from matplotlib.collections import PatchCollection def label(xy, text): y = xy[1] - 0.15 # shift y-value for label so that it's below the artist plt.text(xy[0], y, text, ha="center", family='sans-serif', size=14) fig, ax = plt.subplots() # create 3x3 grid to plot the artists grid = np.mgrid[0.2:0.8:3j, 0.2:0.8:3j].reshape(2, -1).T patches = [] # add a circle circle = mpatches.Circle(grid[0], 0.1, ec="none") patches.append(circle) label(grid[0], "Circle") # add a rectangle rect = mpatches.Rectangle(grid[1] - [0.025, 0.05], 0.05, 0.1, ec="none") patches.append(rect) label(grid[1], "Rectangle") # add a wedge wedge = mpatches.Wedge(grid[2], 0.1, 30, 270, ec="none") patches.append(wedge) label(grid[2], "Wedge") # add a Polygon polygon = mpatches.RegularPolygon(grid[3], 5, 0.1) patches.append(polygon) label(grid[3], "Polygon") # add an ellipse ellipse = mpatches.Ellipse(grid[4], 0.2, 0.1) patches.append(ellipse) label(grid[4], "Ellipse") # add an arrow arrow = mpatches.Arrow(grid[5, 0] - 0.05, grid[5, 1] - 0.05, 0.1, 0.1, width=0.1) patches.append(arrow) label(grid[5], "Arrow") # add a path patch Path = mpath.Path path_data = [ (Path.MOVETO, [0.018, -0.11]), (Path.CURVE4, [-0.031, -0.051]), (Path.CURVE4, [-0.115, 0.073]), (Path.CURVE4, [-0.03, 0.073]), (Path.LINETO, [-0.011, 0.039]), (Path.CURVE4, [0.043, 0.121]), (Path.CURVE4, [0.075, -0.005]), (Path.CURVE4, [0.035, -0.027]), (Path.CLOSEPOLY, [0.018, -0.11])] codes, verts = zip(*path_data) path = mpath.Path(verts + grid[6], codes) patch = mpatches.PathPatch(path) patches.append(patch) label(grid[6], "PathPatch") # add a fancy box fancybox = mpatches.FancyBboxPatch( grid[7] - [0.025, 0.05], 0.05, 0.1, boxstyle=mpatches.BoxStyle("Round", pad=0.02)) patches.append(fancybox) label(grid[7], "FancyBboxPatch") # add a line x, y = np.array([[-0.06, 0.0, 0.1], [0.05, -0.05, 0.05]]) line = mlines.Line2D(x + grid[8, 0], y + grid[8, 1], lw=5., alpha=0.3) label(grid[8], "Line2D") colors = np.linspace(0, 1, len(patches)) collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3) collection.set_array(np.array(colors)) ax.add_collection(collection) ax.add_line(line) plt.axis('equal') plt.axis('off') plt.tight_layout() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.path matplotlib.path.Path matplotlib.lines matplotlib.lines.Line2D matplotlib.patches matplotlib.patches.Circle matplotlib.patches.Ellipse matplotlib.patches.Wedge matplotlib.patches.Rectangle matplotlib.patches.Arrow matplotlib.patches.PathPatch matplotlib.patches.FancyBboxPatch matplotlib.patches.RegularPolygon matplotlib.collections matplotlib.collections.PatchCollection matplotlib.cm.ScalarMappable.set_array matplotlib.axes.Axes.add_collection matplotlib.axes.Axes.add_line
907e1099227af27260694d8fdb852a1f0e1ecba8af17224737f55be317f03aa0
""" ============= Fancybox Demo ============= Plotting fancy boxes with Matplotlib. The following examples show how to plot boxes with different visual properties. """ import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms import matplotlib.patches as mpatch from matplotlib.patches import FancyBboxPatch ############################################################################### # First we'll show some sample boxes with fancybox. styles = mpatch.BoxStyle.get_styles() spacing = 1.2 figheight = (spacing * len(styles) + .5) fig = plt.figure(figsize=(4 / 1.5, figheight / 1.5)) fontsize = 0.3 * 72 for i, stylename in enumerate(sorted(styles)): fig.text(0.5, (spacing * (len(styles) - i) - 0.5) / figheight, stylename, ha="center", size=fontsize, transform=fig.transFigure, bbox=dict(boxstyle=stylename, fc="w", ec="k")) plt.show() ############################################################################### # Next we'll show off multiple fancy boxes at once. # Bbox object around which the fancy box will be drawn. bb = mtransforms.Bbox([[0.3, 0.4], [0.7, 0.6]]) def draw_bbox(ax, bb): # boxstyle=square with pad=0, i.e. bbox itself. p_bbox = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="square,pad=0.", ec="k", fc="none", zorder=10., ) ax.add_patch(p_bbox) def test1(ax): # a fancy box with round corners. pad=0.1 p_fancy = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.1", fc=(1., .8, 1.), ec=(1., 0.5, 1.)) ax.add_patch(p_fancy) ax.text(0.1, 0.8, r' boxstyle="round,pad=0.1"', size=10, transform=ax.transAxes) # draws control points for the fancy box. # l = p_fancy.get_path().vertices # ax.plot(l[:,0], l[:,1], ".") # draw the original bbox in black draw_bbox(ax, bb) def test2(ax): # bbox=round has two optional argument. pad and rounding_size. # They can be set during the initialization. p_fancy = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.1", fc=(1., .8, 1.), ec=(1., 0.5, 1.)) ax.add_patch(p_fancy) # boxstyle and its argument can be later modified with # set_boxstyle method. Note that the old attributes are simply # forgotten even if the boxstyle name is same. p_fancy.set_boxstyle("round,pad=0.1, rounding_size=0.2") # or # p_fancy.set_boxstyle("round", pad=0.1, rounding_size=0.2) ax.text(0.1, 0.8, ' boxstyle="round,pad=0.1\n rounding_size=0.2"', size=10, transform=ax.transAxes) # draws control points for the fancy box. # l = p_fancy.get_path().vertices # ax.plot(l[:,0], l[:,1], ".") draw_bbox(ax, bb) def test3(ax): # mutation_scale determine overall scale of the mutation, # i.e. both pad and rounding_size is scaled according to this # value. p_fancy = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.1", mutation_scale=2., fc=(1., .8, 1.), ec=(1., 0.5, 1.)) ax.add_patch(p_fancy) ax.text(0.1, 0.8, ' boxstyle="round,pad=0.1"\n mutation_scale=2', size=10, transform=ax.transAxes) # draws control points for the fancy box. # l = p_fancy.get_path().vertices # ax.plot(l[:,0], l[:,1], ".") draw_bbox(ax, bb) def test4(ax): # When the aspect ratio of the axes is not 1, the fancy box may # not be what you expected (green) p_fancy = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.2", fc="none", ec=(0., .5, 0.), zorder=4) ax.add_patch(p_fancy) # You can compensate this by setting the mutation_aspect (pink). p_fancy = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.3", mutation_aspect=.5, fc=(1., 0.8, 1.), ec=(1., 0.5, 1.)) ax.add_patch(p_fancy) ax.text(0.1, 0.8, ' boxstyle="round,pad=0.3"\n mutation_aspect=.5', size=10, transform=ax.transAxes) draw_bbox(ax, bb) def test_all(): plt.clf() ax = plt.subplot(2, 2, 1) test1(ax) ax.set_xlim(0., 1.) ax.set_ylim(0., 1.) ax.set_title("test1") ax.set_aspect(1.) ax = plt.subplot(2, 2, 2) ax.set_title("test2") test2(ax) ax.set_xlim(0., 1.) ax.set_ylim(0., 1.) ax.set_aspect(1.) ax = plt.subplot(2, 2, 3) ax.set_title("test3") test3(ax) ax.set_xlim(0., 1.) ax.set_ylim(0., 1.) ax.set_aspect(1) ax = plt.subplot(2, 2, 4) ax.set_title("test4") test4(ax) ax.set_xlim(-0.5, 1.5) ax.set_ylim(0., 1.) ax.set_aspect(2.) plt.show() test_all() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.patches matplotlib.patches.FancyBboxPatch matplotlib.patches.BoxStyle matplotlib.patches.BoxStyle.get_styles matplotlib.transforms.Bbox
7595a49512d71f31a302a396853e50c7cb24d33b38f7b5657333adc3b8642b9d
r""" ============= Mmh Donuts!!! ============= Draw donuts (miam!) using `~.path.Path`\s and `~.patches.PathPatch`\es. This example shows the effect of the path's orientations in a compound path. """ import numpy as np import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt def wise(v): if v == 1: return "CCW" else: return "CW" def make_circle(r): t = np.arange(0, np.pi * 2.0, 0.01) t = t.reshape((len(t), 1)) x = r * np.cos(t) y = r * np.sin(t) return np.hstack((x, y)) Path = mpath.Path fig, ax = plt.subplots() inside_vertices = make_circle(0.5) outside_vertices = make_circle(1.0) codes = np.ones( len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO codes[0] = mpath.Path.MOVETO for i, (inside, outside) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))): # Concatenate the inside and outside subpaths together, changing their # order as needed vertices = np.concatenate((outside_vertices[::outside], inside_vertices[::inside])) # Shift the path vertices[:, 0] += i * 2.5 # The codes will be all "LINETO" commands, except for "MOVETO"s at the # beginning of each subpath all_codes = np.concatenate((codes, codes)) # Create the Path object path = mpath.Path(vertices, all_codes) # Add plot it patch = mpatches.PathPatch(path, facecolor='#885500', edgecolor='black') ax.add_patch(patch) ax.annotate("Outside %s,\nInside %s" % (wise(outside), wise(inside)), (i * 2.5, -1.5), va="top", ha="center") ax.set_xlim(-2, 10) ax.set_ylim(-3, 2) ax.set_title('Mmm, donuts!') ax.set_aspect(1.0) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.path matplotlib.path.Path matplotlib.patches matplotlib.patches.PathPatch matplotlib.patches.Circle matplotlib.axes.Axes.add_patch matplotlib.axes.Axes.annotate matplotlib.axes.Axes.set_aspect matplotlib.axes.Axes.set_xlim matplotlib.axes.Axes.set_ylim matplotlib.axes.Axes.set_title
ad98da5551785189b112cca18a29351629ba3fc782581af5209dffb3cdd6db9e
""" ==================== List of named colors ==================== This plots a list of the named colors supported in matplotlib. Note that :ref:`xkcd colors <xkcd-colors>` are supported as well, but are not listed here for brevity. For more information on colors in matplotlib see * the :doc:`/tutorials/colors/colors` tutorial; * the `matplotlib.colors` API; * the :doc:`/gallery/color/color_demo`. """ import matplotlib.pyplot as plt import matplotlib.colors as mcolors def plot_colortable(colors, title, sort_colors=True, emptycols=0): cell_width = 212 cell_height = 22 swatch_width = 48 margin = 12 topmargin = 40 # Sort colors by hue, saturation, value and name. if sort_colors is True: by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))), name) for name, color in colors.items()) names = [name for hsv, name in by_hsv] else: names = list(colors) n = len(names) ncols = 4 - emptycols nrows = n // ncols + int(n % ncols > 0) width = cell_width * 4 + 2 * margin height = cell_height * nrows + margin + topmargin dpi = 72 fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi) fig.subplots_adjust(margin/width, margin/height, (width-margin)/width, (height-topmargin)/height) ax.set_xlim(0, cell_width * 4) ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.) ax.yaxis.set_visible(False) ax.xaxis.set_visible(False) ax.set_axis_off() ax.set_title(title, fontsize=24, loc="left", pad=10) for i, name in enumerate(names): row = i % nrows col = i // nrows y = row * cell_height swatch_start_x = cell_width * col swatch_end_x = cell_width * col + swatch_width text_pos_x = cell_width * col + swatch_width + 7 ax.text(text_pos_x, y, name, fontsize=14, horizontalalignment='left', verticalalignment='center') ax.hlines(y, swatch_start_x, swatch_end_x, color=colors[name], linewidth=18) return fig plot_colortable(mcolors.BASE_COLORS, "Base Colors", sort_colors=False, emptycols=1) plot_colortable(mcolors.TABLEAU_COLORS, "Tableau Palette", sort_colors=False, emptycols=2) #sphinx_gallery_thumbnail_number = 3 plot_colortable(mcolors.CSS4_COLORS, "CSS Colors") # Optionally plot the XKCD colors (Caution: will produce large figure) #xkcd_fig = plot_colortable(mcolors.XKCD_COLORS, "XKCD Colors") #xkcd_fig.savefig("XKCD_Colors.png") plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.colors matplotlib.colors.rgb_to_hsv matplotlib.colors.to_rgba matplotlib.figure.Figure.get_size_inches matplotlib.figure.Figure.subplots_adjust matplotlib.axes.Axes.text matplotlib.axes.Axes.hlines
d782a0d85319ef466e18e2d107c19de144c4eb5c6963f7e2519f629893757216
""" ================== Colormap reference ================== Reference for colormaps included with Matplotlib. A reversed version of each of these colormaps is available by appending ``_r`` to the name, e.g., ``viridis_r``. See :doc:`/tutorials/colors/colormaps` for an in-depth discussion about colormaps, including colorblind-friendliness. """ import numpy as np import matplotlib.pyplot as plt cmaps = [('Perceptually Uniform Sequential', [ 'viridis', 'plasma', 'inferno', 'magma', 'cividis']), ('Sequential', [ 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']), ('Sequential (2)', [ 'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink', 'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper']), ('Diverging', [ 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']), ('Cyclic', ['twilight', 'twilight_shifted', 'hsv']), ('Qualitative', [ 'Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c']), ('Miscellaneous', [ 'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet', 'nipy_spectral', 'gist_ncar'])] gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) def plot_color_gradients(cmap_category, cmap_list): # Create figure and adjust figure height to number of colormaps nrows = len(cmap_list) figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22 fig, axes = plt.subplots(nrows=nrows, figsize=(6.4, figh)) fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99) axes[0].set_title(cmap_category + ' colormaps', fontsize=14) for ax, name in zip(axes, cmap_list): ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name)) ax.text(-.01, .5, name, va='center', ha='right', fontsize=10, transform=ax.transAxes) # Turn off *all* ticks & spines, not just the ones with colormaps. for ax in axes: ax.set_axis_off() for cmap_category, cmap_list in cmaps: plot_color_gradients(cmap_category, cmap_list) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.colors matplotlib.axes.Axes.imshow matplotlib.figure.Figure.text matplotlib.axes.Axes.set_axis_off
983881d9fd189139eb11df26fba5736369cf3306a42ccc8da6d3b0a20df54265
""" ==================================== Colors in the default property cycle ==================================== Display the colors from the default prop_cycle, which is obtained from the :doc:`rc parameters</tutorials/introductory/customizing>`. """ import numpy as np import matplotlib.pyplot as plt prop_cycle = plt.rcParams['axes.prop_cycle'] colors = prop_cycle.by_key()['color'] lwbase = plt.rcParams['lines.linewidth'] thin = lwbase / 2 thick = lwbase * 3 fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True) for icol in range(2): if icol == 0: lwx, lwy = thin, lwbase else: lwx, lwy = lwbase, thick for irow in range(2): for i, color in enumerate(colors): axs[irow, icol].axhline(i, color=color, lw=lwx) axs[irow, icol].axvline(i, color=color, lw=lwy) axs[1, icol].set_facecolor('k') axs[1, icol].xaxis.set_ticks(np.arange(0, 10, 2)) axs[0, icol].set_title('line widths (pts): %g, %g' % (lwx, lwy), fontsize='medium') for irow in range(2): axs[irow, 0].yaxis.set_ticks(np.arange(0, 10, 2)) fig.suptitle('Colors in the default prop_cycle', fontsize='large') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.axhline matplotlib.axes.Axes.axvline matplotlib.pyplot.axhline matplotlib.pyplot.axvline matplotlib.axes.Axes.set_facecolor matplotlib.figure.Figure.suptitle
56b9507bcec8a8972ece0ebc1b7272c53fdd426585e40de24baa2346321331aa
""" ================ Color by y-value ================ Use masked arrays to plot a line with different colors by y-value. """ import numpy as np import matplotlib.pyplot as plt t = np.arange(0.0, 2.0, 0.01) s = np.sin(2 * np.pi * t) upper = 0.77 lower = -0.77 supper = np.ma.masked_where(s < upper, s) slower = np.ma.masked_where(s > lower, s) smiddle = np.ma.masked_where((s < lower) | (s > upper), s) fig, ax = plt.subplots() ax.plot(t, smiddle, t, slower, t, supper) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.plot matplotlib.pyplot.plot
9fc5d1e4ce84a853be6610c4c84481df856ab99ded9421f2c19af806e93faa48
""" ========================================= Creating a colormap from a list of colors ========================================= For more detail on creating and manipulating colormaps see :doc:`/tutorials/colors/colormap-manipulation`. Creating a :doc:`colormap </tutorials/colors/colormaps>` from a list of colors can be done with the :meth:`~.colors.LinearSegmentedColormap.from_list` method of `LinearSegmentedColormap`. You must pass a list of RGB tuples that define the mixture of colors from 0 to 1. Creating custom colormaps ------------------------- It is also possible to create a custom mapping for a colormap. This is accomplished by creating dictionary that specifies how the RGB channels change from one end of the cmap to the other. 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.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.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 y1 / / 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. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap # Make some illustrative fake data: 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) * 10 ############################################################################### # --- Colormaps from a list --- colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] # R -> G -> B n_bins = [3, 6, 10, 100] # Discretizes the interpolation into bins cmap_name = 'my_list' fig, axs = plt.subplots(2, 2, figsize=(6, 9)) fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05) for n_bin, ax in zip(n_bins, axs.ravel()): # Create the colormap cm = LinearSegmentedColormap.from_list( cmap_name, colors, N=n_bin) # Fewer bins will result in "coarser" colomap interpolation im = ax.imshow(Z, interpolation='nearest', origin='lower', cmap=cm) ax.set_title("N bins: %s" % n_bin) fig.colorbar(im, ax=ax) ############################################################################### # --- Custom colormaps --- 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': ((0.0, 0.0, 1.0), (0.5, 0.1, 0.0), (1.0, 0.0, 0.0)) } cdict2 = {'red': ((0.0, 0.0, 0.0), (0.5, 0.0, 1.0), (1.0, 0.1, 1.0)), 'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.1), (0.5, 1.0, 0.0), (1.0, 0.0, 0.0)) } cdict3 = {'red': ((0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 0.8, 1.0), (0.75, 1.0, 1.0), (1.0, 0.4, 1.0)), 'green': ((0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 0.9, 0.9), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.4), (0.25, 1.0, 1.0), (0.5, 1.0, 0.8), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)) } # Make a modified version of cdict3 with some transparency # in the middle of the range. cdict4 = {**cdict3, 'alpha': ((0.0, 1.0, 1.0), # (0.25,1.0, 1.0), (0.5, 0.3, 0.3), # (0.75,1.0, 1.0), (1.0, 1.0, 1.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 plt.register_cmap(name='BlueRedAlpha', data=cdict4) ############################################################################### # Make the figure: fig, axs = plt.subplots(2, 2, figsize=(6, 9)) fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05) # Make 4 subplots: im1 = axs[0, 0].imshow(Z, interpolation='nearest', cmap=blue_red1) fig.colorbar(im1, ax=axs[0, 0]) cmap = plt.get_cmap('BlueRed2') im2 = axs[1, 0].imshow(Z, interpolation='nearest', cmap=cmap) fig.colorbar(im2, ax=axs[1, 0]) # 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' im3 = axs[0, 1].imshow(Z, interpolation='nearest') fig.colorbar(im3, ax=axs[0, 1]) axs[0, 1].set_title("Alpha = 1") # Or as yet another variation, we can replace the rcParams # specification *before* the imshow with the following *after* # imshow. # This sets the new default *and* sets the colormap of the last # image-like item plotted via pyplot, if any. # # Draw a line with low zorder so it will be behind the image. axs[1, 1].plot([0, 10 * np.pi], [0, 20 * np.pi], color='c', lw=20, zorder=-1) im4 = axs[1, 1].imshow(Z, interpolation='nearest') fig.colorbar(im4, ax=axs[1, 1]) # Here it is: changing the colormap for the current image and its # colorbar after they have been plotted. im4.set_cmap('BlueRedAlpha') axs[1, 1].set_title("Varying alpha") # fig.suptitle('Custom Blue-Red colormaps', fontsize=16) fig.subplots_adjust(top=0.9) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.colors matplotlib.colors.LinearSegmentedColormap matplotlib.colors.LinearSegmentedColormap.from_list matplotlib.cm matplotlib.cm.ScalarMappable.set_cmap matplotlib.pyplot.register_cmap matplotlib.cm.register_cmap
5fa9c55d397cc2b724aefbd0e77a8f8cd9303b1ff66f2dde99eec40c8e9cb779
""" =================== Styling with cycler =================== Demo of custom property-cycle settings to control colors and other style properties for multi-line plots. This example demonstrates two different APIs: 1. Setting the default :doc:`rc parameter</tutorials/introductory/customizing>` specifying the property cycle. This affects all subsequent axes (but not axes already created). 2. Setting the property cycle for a single pair of axes. """ from cycler import cycler import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi) offsets = np.linspace(0, 2*np.pi, 4, endpoint=False) # Create array with shifted-sine curve along each column yy = np.transpose([np.sin(x + phi) for phi in offsets]) # 1. Setting prop cycle on default rc parameter plt.rc('lines', linewidth=4) plt.rc('axes', prop_cycle=(cycler(color=['r', 'g', 'b', 'y']) + cycler(linestyle=['-', '--', ':', '-.']))) fig, (ax0, ax1) = plt.subplots(nrows=2, constrained_layout=True) ax0.plot(yy) ax0.set_title('Set default color cycle to rgby') # 2. Define prop cycle for single set of axes # For the most general use-case, you can provide a cycler to # `.set_prop_cycle`. # Here, we use the convenient shortcut that we can alternatively pass # one or more properties as keyword arguments. This creates and sets # a cycler iterating simultaneously over all properties. ax1.set_prop_cycle(color=['c', 'm', 'y', 'k'], lw=[1, 2, 3, 4]) ax1.plot(yy) ax1.set_title('Set axes color cycle to cmyk') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.plot matplotlib.axes.Axes.set_prop_cycle
fe502ca31198ac49d53d4355fe2d866aade8dde6984e21f73d04453a1ddf9d90
""" ========== Color Demo ========== Matplotlib recognizes the following formats to specify a color: 1) an RGB or RGBA tuple of float values in ``[0, 1]`` (e.g. ``(0.1, 0.2, 0.5)`` or ``(0.1, 0.2, 0.5, 0.3)``). RGBA is short for Red, Green, Blue, Alpha; 2) a hex RGB or RGBA string (e.g., ``'#0F0F0F'`` or ``'#0F0F0F0F'``); 3) a string representation of a float value in ``[0, 1]`` inclusive for gray level (e.g., ``'0.5'``); 4) a single letter string, i.e. one of ``{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}``; 5) a X11/CSS4 ("html") color name, e.g. ``"blue"``; 6) a name from the `xkcd color survey <https://xkcd.com/color/rgb/>`__, prefixed with ``'xkcd:'`` (e.g., ``'xkcd:sky blue'``); 7) a "Cn" color spec, i.e. `'C'` followed by a number, which is an index into the default property cycle (``matplotlib.rcParams['axes.prop_cycle']``); the indexing is intended to occur at rendering time, and defaults to black if the cycle does not include color. 8) one of ``{'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'}`` which are the Tableau Colors from the 'tab10' categorical palette (which is the default color cycle); For more information on colors in matplotlib see * the :doc:`/tutorials/colors/colors` tutorial; * the `matplotlib.colors` API; * the :doc:`/gallery/color/named_colors` example. """ import matplotlib.pyplot as plt import numpy as np t = np.linspace(0.0, 2.0, 201) s = np.sin(2 * np.pi * t) # 1) RGB tuple: fig, ax = plt.subplots(facecolor=(.18, .31, .31)) # 2) hex string: ax.set_facecolor('#eafff5') # 3) gray level string: ax.set_title('Voltage vs. time chart', color='0.7') # 4) single letter color string ax.set_xlabel('time (s)', color='c') # 5) a named color: ax.set_ylabel('voltage (mV)', color='peachpuff') # 6) a named xkcd color: ax.plot(t, s, 'xkcd:crimson') # 7) Cn notation: ax.plot(t, .7*s, color='C4', linestyle='--') # 8) tab notation: ax.tick_params(labelcolor='tab:orange') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.colors matplotlib.axes.Axes.plot matplotlib.axes.Axes.set_facecolor matplotlib.axes.Axes.set_title matplotlib.axes.Axes.set_xlabel matplotlib.axes.Axes.set_ylabel matplotlib.axes.Axes.tick_params
e2470e0c2dce4851be7209aacac2d9fed81b7b738f5528484b5c1aed36999237
""" ======== Colorbar ======== Use `~.figure.Figure.colorbar` by specifying the mappable object (here the `~.matplotlib.image.AxesImage` returned by `~.axes.Axes.imshow`) and the axes to attach the colorbar to. """ import numpy as np import matplotlib.pyplot as plt # setup some generic data N = 37 x, y = np.mgrid[:N, :N] Z = (np.cos(x*0.2) + np.sin(y*0.3)) # mask out the negative and positive values, respectively Zpos = np.ma.masked_less(Z, 0) Zneg = np.ma.masked_greater(Z, 0) fig, (ax1, ax2, ax3) = plt.subplots(figsize=(13, 3), ncols=3) # plot just the positive data and save the # color "mappable" object returned by ax1.imshow pos = ax1.imshow(Zpos, cmap='Blues', interpolation='none') # add the colorbar using the figure's method, # telling which mappable we're talking about and # which axes object it should be near fig.colorbar(pos, ax=ax1) # repeat everything above for the negative data neg = ax2.imshow(Zneg, cmap='Reds_r', interpolation='none') fig.colorbar(neg, ax=ax2) # Plot both positive and negative values between +/- 1.2 pos_neg_clipped = ax3.imshow(Z, cmap='RdBu', vmin=-1.2, vmax=1.2, interpolation='none') # Add minorticks on the colorbar to make it easy to read the # values off the colorbar. cbar = fig.colorbar(pos_neg_clipped, ax=ax3, extend='both') cbar.minorticks_on() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib import matplotlib.colorbar matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.colorbar.Colorbar.minorticks_on matplotlib.colorbar.Colorbar.minorticks_off
fc57a858fad503584db7160655eb784b002956598ef6282ed6e487f152536938
""" Fixing common date annoyances ============================= Matplotlib allows you to natively plots python datetime instances, and for the most part does a good job picking tick locations and string formats. There are a couple of things it does not handle so gracefully, and here are some tricks to help you work around them. We'll load up some sample date data which contains datetime.date objects in a numpy record array:: In [63]: datafile = cbook.get_sample_data('goog.npz') In [64]: r = np.load(datafile)['price_data'].view(np.recarray) In [65]: r.dtype Out[65]: dtype([('date', '<M8[D]'), ('', '|V4'), ('open', '<f8'), ('high', '<f8'), ('low', '<f8'), ('close', '<f8'), ('volume', '<i8'), ('adj_close', '<f8')]) In [66]: r.date Out[66]: array(['2004-08-19', '2004-08-20', '2004-08-23', ..., '2008-10-10', '2008-10-13', '2008-10-14'], dtype='datetime64[D]') The dtype of the NumPy record array for the field ``date`` is ``datetime64[D]`` which means it is a 64-bit `np.datetime64` in 'day' units. While this format is more portable, Matplotlib cannot plot this format natively yet. We can plot this data by changing the dates to `datetime.date` instances instead, which can be achieved by converting to an object array:: In [67]: r.date.astype('O') array([datetime.date(2004, 8, 19), datetime.date(2004, 8, 20), datetime.date(2004, 8, 23), ..., datetime.date(2008, 10, 10), datetime.date(2008, 10, 13), datetime.date(2008, 10, 14)], dtype=object) The dtype of this converted array is now ``object`` and it is filled with datetime.date instances instead. If you plot the data, :: In [67]: plot(r.date.astype('O'), r.close) Out[67]: [<matplotlib.lines.Line2D object at 0x92a6b6c>] you will see that the x tick labels are all squashed together. """ import matplotlib.cbook as cbook import matplotlib.dates as mdates import numpy as np import matplotlib.pyplot as plt with cbook.get_sample_data('goog.npz') as datafile: r = np.load(datafile)['price_data'].view(np.recarray) # Matplotlib prefers datetime instead of np.datetime64. date = r.date.astype('O') fig, ax = plt.subplots() ax.plot(date, r.close) ax.set_title('Default date handling can cause overlapping labels') ############################################################################### # Another annoyance is that if you hover the mouse over the window and # look in the lower right corner of the matplotlib toolbar # (:ref:`navigation-toolbar`) at the x and y coordinates, you see that # the x locations are formatted the same way the tick labels are, e.g., # "Dec 2004". # # What we'd like is for the location in the toolbar to have # a higher degree of precision, e.g., giving us the exact date out mouse is # hovering over. To fix the first problem, we can use # :func:`matplotlib.figure.Figure.autofmt_xdate` and to fix the second # problem we can use the ``ax.fmt_xdata`` attribute which can be set to # any function that takes a scalar and returns a string. matplotlib has # a number of date formatters built in, so we'll use one of those. fig, ax = plt.subplots() ax.plot(date, r.close) # rotate and align the tick labels so they look better fig.autofmt_xdate() # use a more precise date string for the x axis locations in the # toolbar ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d') ax.set_title('fig.autofmt_xdate fixes the labels') ############################################################################### # Now when you hover your mouse over the plotted data, you'll see date # format strings like 2004-12-01 in the toolbar. plt.show()
c6f0855fc1d5bd3703c993bdae1eea7557575b09a7e76936e746e3b590221526
""" Fill Between and Alpha ====================== The :meth:`~matplotlib.axes.Axes.fill_between` function generates a shaded region between a min and max boundary that is useful for illustrating ranges. It has a very handy ``where`` argument to combine filling with logical ranges, e.g., to just fill in a curve over some threshold value. At its most basic level, ``fill_between`` can be use to enhance a graphs visual appearance. Let's compare two graphs of a financial times with a simple line plot on the left and a filled line on the right. """ import matplotlib.pyplot as plt import numpy as np import matplotlib.cbook as cbook # load up some sample financial data with cbook.get_sample_data('goog.npz') as datafile: r = np.load(datafile)['price_data'].view(np.recarray) # Matplotlib prefers datetime instead of np.datetime64. date = r.date.astype('O') # create two subplots with the shared x and y axes fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True) pricemin = r.close.min() ax1.plot(date, r.close, lw=2) ax2.fill_between(date, pricemin, r.close, facecolor='blue', alpha=0.5) for ax in ax1, ax2: ax.grid(True) ax1.set_ylabel('price') for label in ax2.get_yticklabels(): label.set_visible(False) fig.suptitle('Google (GOOG) daily closing price') fig.autofmt_xdate() ############################################################################### # The alpha channel is not necessary here, but it can be used to soften # colors for more visually appealing plots. In other examples, as we'll # see below, the alpha channel is functionally useful as the shaded # regions can overlap and alpha allows you to see both. Note that the # postscript format does not support alpha (this is a postscript # limitation, not a matplotlib limitation), so when using alpha save # your figures in PNG, PDF or SVG. # # Our next example computes two populations of random walkers with a # different mean and standard deviation of the normal distributions from # which the steps are drawn. We use shared regions to plot +/- one # standard deviation of the mean position of the population. Here the # alpha channel is useful, not just aesthetic. Nsteps, Nwalkers = 100, 250 t = np.arange(Nsteps) # an (Nsteps x Nwalkers) array of random walk steps S1 = 0.002 + 0.01*np.random.randn(Nsteps, Nwalkers) S2 = 0.004 + 0.02*np.random.randn(Nsteps, Nwalkers) # an (Nsteps x Nwalkers) array of random walker positions X1 = S1.cumsum(axis=0) X2 = S2.cumsum(axis=0) # Nsteps length arrays empirical means and standard deviations of both # populations over time mu1 = X1.mean(axis=1) sigma1 = X1.std(axis=1) mu2 = X2.mean(axis=1) sigma2 = X2.std(axis=1) # plot it! fig, ax = plt.subplots(1) ax.plot(t, mu1, lw=2, label='mean population 1', color='blue') ax.plot(t, mu2, lw=2, label='mean population 2', color='yellow') ax.fill_between(t, mu1+sigma1, mu1-sigma1, facecolor='blue', alpha=0.5) ax.fill_between(t, mu2+sigma2, mu2-sigma2, facecolor='yellow', alpha=0.5) ax.set_title(r'random walkers empirical $\mu$ and $\pm \sigma$ interval') ax.legend(loc='upper left') ax.set_xlabel('num steps') ax.set_ylabel('position') ax.grid() ############################################################################### # The ``where`` keyword argument is very handy for highlighting certain # regions of the graph. ``where`` takes a boolean mask the same length # as the x, ymin and ymax arguments, and only fills in the region where # the boolean mask is True. In the example below, we simulate a single # random walker and compute the analytic mean and standard deviation of # the population positions. The population mean is shown as the black # dashed line, and the plus/minus one sigma deviation from the mean is # shown as the yellow filled region. We use the where mask # ``X > upper_bound`` to find the region where the walker is above the one # sigma boundary, and shade that region blue. Nsteps = 500 t = np.arange(Nsteps) mu = 0.002 sigma = 0.01 # the steps and position S = mu + sigma*np.random.randn(Nsteps) X = S.cumsum() # the 1 sigma upper and lower analytic population bounds lower_bound = mu*t - sigma*np.sqrt(t) upper_bound = mu*t + sigma*np.sqrt(t) fig, ax = plt.subplots(1) ax.plot(t, X, lw=2, label='walker position', color='blue') ax.plot(t, mu*t, lw=1, label='population mean', color='black', ls='--') ax.fill_between(t, lower_bound, upper_bound, facecolor='yellow', alpha=0.5, label='1 sigma range') ax.legend(loc='upper left') # here we use the where argument to only fill the region where the # walker is above the population 1 sigma boundary ax.fill_between(t, upper_bound, X, where=X > upper_bound, facecolor='blue', alpha=0.5) ax.set_xlabel('num steps') ax.set_ylabel('position') ax.grid() ############################################################################### # Another handy use of filled regions is to highlight horizontal or # vertical spans of an axes -- for that matplotlib has some helper # functions :meth:`~matplotlib.axes.Axes.axhspan` and # :meth:`~matplotlib.axes.Axes.axvspan` and example # :doc:`/gallery/subplots_axes_and_figures/axhspan_demo`. plt.show()
0bc5299cb0bae39344d512030710085f1747780b5a7d07f6f6029a420fd67c5e
""" Easily creating subplots ======================== In early versions of matplotlib, if you wanted to use the pythonic API and create a figure instance and from that create a grid of subplots, possibly with shared axes, it involved a fair amount of boilerplate code. e.g. """ import matplotlib.pyplot as plt import numpy as np x = np.random.randn(50) # old style fig = plt.figure() ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222, sharex=ax1, sharey=ax1) ax3 = fig.add_subplot(223, sharex=ax1, sharey=ax1) ax3 = fig.add_subplot(224, sharex=ax1, sharey=ax1) ############################################################################### # Fernando Perez has provided a nice top level method to create in # :func:`~matplotlib.pyplots.subplots` (note the "s" at the end) # everything at once, and turn on x and y sharing for the whole bunch. # You can either unpack the axes individually... # new style method 1; unpack the axes fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex=True, sharey=True) ax1.plot(x) ############################################################################### # or get them back as a numrows x numcolumns object array which supports # numpy indexing # new style method 2; use an axes array fig, axs = plt.subplots(2, 2, sharex=True, sharey=True) axs[0, 0].plot(x) plt.show()
b1034d482f920860b906268f4bded11eb9212b9341cc327af22d579ef109c588
""" Sharing axis limits and views ============================= It's common to make two or more plots which share an axis, e.g., two subplots with time as a common axis. When you pan and zoom around on one, you want the other to move around with you. To facilitate this, matplotlib Axes support a ``sharex`` and ``sharey`` attribute. When you create a :func:`~matplotlib.pyplot.subplot` or :func:`~matplotlib.pyplot.axes` instance, you can pass in a keyword indicating what axes you want to share with """ import numpy as np import matplotlib.pyplot as plt t = np.arange(0, 10, 0.01) ax1 = plt.subplot(211) ax1.plot(t, np.sin(2*np.pi*t)) ax2 = plt.subplot(212, sharex=ax1) ax2.plot(t, np.sin(4*np.pi*t)) plt.show()
acf4c736202676c282b89c2d15f6730fbedcedca9d3f636a8bf04e0ce90219f0
""" Placing text boxes ================== When decorating axes with text boxes, two useful tricks are to place the text in axes coordinates (see :doc:`/tutorials/advanced/transforms_tutorial`), so the text doesn't move around with changes in x or y limits. You can also use the ``bbox`` property of text to surround the text with a :class:`~matplotlib.patches.Patch` instance -- the ``bbox`` keyword argument takes a dictionary with keys that are Patch properties. """ import numpy as np import matplotlib.pyplot as plt np.random.seed(19680801) fig, ax = plt.subplots() x = 30*np.random.randn(10000) mu = x.mean() median = np.median(x) sigma = x.std() textstr = '\n'.join(( r'$\mu=%.2f$' % (mu, ), r'$\mathrm{median}=%.2f$' % (median, ), r'$\sigma=%.2f$' % (sigma, ))) ax.hist(x, 50) # these are matplotlib.patch.Patch properties props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) # place a text box in upper left in axes coords ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14, verticalalignment='top', bbox=props) plt.show()
10e5a9175f36e4c53832c1c085e2e3537a278c6bd5e863665f14021532fdd29e
#!/usr/bin/env python # # This script generates credits.rst with an up-to-date list of contributors # to the matplotlib github repository. from collections import Counter import locale import re import subprocess TEMPLATE = """.. Note: This file is auto-generated using generate_credits.py .. _credits: ******* Credits ******* Matplotlib was written by John D. Hunter, with contributions from an ever-increasing number of users and developers. The current co-lead developers are Michael Droettboom and Thomas A. Caswell; they are assisted by many `active <https://www.openhub.net/p/matplotlib/contributors>`_ developers. The following is a list of contributors extracted from the git revision control history of the project: {contributors} Some earlier contributors not included above are (with apologies to any we have missed): Charles Twardy, Gary Ruben, John Gill, David Moore, Paul Barrett, Jared Wahlstrand, Jim Benson, Paul Mcguire, Andrew Dalke, Nadia Dencheva, Baptiste Carvello, Sigve Tjoraand, Ted Drain, James Amundson, Daishi Harada, Nicolas Young, Paul Kienzle, John Porter, and Jonathon Taylor. We also thank all who have reported bugs, commented on proposed changes, or otherwise contributed to Matplotlib's development and usefulness. """ def check_duplicates(): text = subprocess.check_output(['git', 'shortlog', '--summary', '--email']) lines = text.decode('utf8').split('\n') contributors = [line.split('\t', 1)[1].strip() for line in lines if line] emails = [re.match('.*<(.*)>', line).group(1) for line in contributors] email_counter = Counter(emails) if email_counter.most_common(1)[0][1] > 1: print('DUPLICATE CHECK: The following email addresses are used with ' 'more than one name.\nConsider adding them to .mailmap.\n') for email, count in email_counter.items(): if count > 1: print('%s\n%s' % (email, '\n'.join(l for l in lines if email in l))) def generate_credits(): text = subprocess.check_output(['git', 'shortlog', '--summary']) lines = text.decode('utf8').split('\n') contributors = [line.split('\t', 1)[1].strip() for line in lines if line] contributors.sort(key=locale.strxfrm) with open('credits.rst', 'w') as f: f.write(TEMPLATE.format(contributors=',\n'.join(contributors))) if __name__ == '__main__': check_duplicates() generate_credits()
1d498b7c95e751805570cab4dfb6b07324e23cb370ffb975ec8c83cca71e0e2e
from docutils import nodes from os.path import sep def rcparam_role(name, rawtext, text, lineno, inliner, options={}, content=[]): rendered = nodes.Text('rcParams["{}"]'.format(text)) source = inliner.document.attributes['source'].replace(sep, '/') rel_source = source.split('/doc/', 1)[1] levels = rel_source.count('/') refuri = ('../' * levels + 'tutorials/introductory/customizing.html#matplotlib-rcparams') ref = nodes.reference(rawtext, rendered, refuri=refuri) return [nodes.literal('', '', ref)], [] def setup(app): app.add_role("rc", rcparam_role) return {"parallel_read_safe": True, "parallel_write_safe": True}
f3f79640a2315fa0b85ba1c5a0787714a1bdee746c3f296b8b5b90ccfcfd1045
from matplotlib import mathtext symbols = [ ["Lower-case Greek", 6, r"""\alpha \beta \gamma \chi \delta \epsilon \eta \iota \kappa \lambda \mu \nu \omega \phi \pi \psi \rho \sigma \tau \theta \upsilon \xi \zeta \digamma \varepsilon \varkappa \varphi \varpi \varrho \varsigma \vartheta"""], ["Upper-case Greek", 8, r"""\Delta \Gamma \Lambda \Omega \Phi \Pi \Psi \Sigma \Theta \Upsilon \Xi \mho \nabla"""], ["Hebrew", 6, r"""\aleph \beth \daleth \gimel"""], ["Delimiters", 6, r"""| \{ \lfloor / \Uparrow \llcorner \vert \} \rfloor \backslash \uparrow \lrcorner \| \langle \lceil [ \Downarrow \ulcorner \Vert \rangle \rceil ] \downarrow \urcorner"""], ["Big symbols", 6, r"""\bigcap \bigcup \bigodot \bigoplus \bigotimes \biguplus \bigvee \bigwedge \coprod \oint \prod \sum \int"""], ["Standard function names", 6, r"""\arccos \csc \ker \min \arcsin \deg \lg \Pr \arctan \det \lim \gcd \ln \sup \cot \hom \log \tan \coth \inf \max \tanh \sec \arg \dim \liminf \sin \cos \exp \limsup \sinh \cosh"""], ["Binary operation and relation symbols", 4, r"""\ast \pm \slash \cap \star \mp \cup \cdot \uplus \triangleleft \circ \odot \sqcap \triangleright \bullet \ominus \sqcup \bigcirc \oplus \wedge \diamond \oslash \vee \bigtriangledown \times \otimes \dag \bigtriangleup \div \wr \ddag \barwedge \veebar \boxplus \curlywedge \curlyvee \boxminus \Cap \Cup \boxtimes \bot \top \dotplus \boxdot \intercal \rightthreetimes \divideontimes \leftthreetimes \equiv \leq \geq \perp \cong \prec \succ \mid \neq \preceq \succeq \parallel \sim \ll \gg \bowtie \simeq \subset \supset \Join \approx \subseteq \supseteq \ltimes \asymp \sqsubset \sqsupset \rtimes \doteq \sqsubseteq \sqsupseteq \smile \propto \dashv \vdash \frown \models \in \ni \notin \approxeq \leqq \geqq \lessgtr \leqslant \geqslant \lesseqgtr \backsim \lessapprox \gtrapprox \lesseqqgtr \backsimeq \lll \ggg \gtreqqless \triangleq \lessdot \gtrdot \gtreqless \circeq \lesssim \gtrsim \gtrless \bumpeq \eqslantless \eqslantgtr \backepsilon \Bumpeq \precsim \succsim \between \doteqdot \precapprox \succapprox \pitchfork \Subset \Supset \fallingdotseq \subseteqq \supseteqq \risingdotseq \sqsubset \sqsupset \varpropto \preccurlyeq \succcurlyeq \Vdash \therefore \curlyeqprec \curlyeqsucc \vDash \because \blacktriangleleft \blacktriangleright \Vvdash \eqcirc \trianglelefteq \trianglerighteq \neq \vartriangleleft \vartriangleright \ncong \nleq \ngeq \nsubseteq \nmid \nsupseteq \nparallel \nless \ngtr \nprec \nsucc \subsetneq \nsim \supsetneq \nVDash \precnapprox \succnapprox \subsetneqq \nvDash \precnsim \succnsim \supsetneqq \nvdash \lnapprox \gnapprox \ntriangleleft \ntrianglelefteq \lneqq \gneqq \ntriangleright \lnsim \gnsim \ntrianglerighteq \coloneq \eqsim \nequiv \napprox \nsupset \doublebarwedge \nVdash \Doteq \nsubset \eqcolon \ne """], ["Arrow symbols", 4, r"""\leftarrow \longleftarrow \uparrow \Leftarrow \Longleftarrow \Uparrow \rightarrow \longrightarrow \downarrow \Rightarrow \Longrightarrow \Downarrow \leftrightarrow \updownarrow \longleftrightarrow \updownarrow \Leftrightarrow \Longleftrightarrow \Updownarrow \mapsto \longmapsto \nearrow \hookleftarrow \hookrightarrow \searrow \leftharpoonup \rightharpoonup \swarrow \leftharpoondown \rightharpoondown \nwarrow \rightleftharpoons \leadsto \dashrightarrow \dashleftarrow \leftleftarrows \leftrightarrows \Lleftarrow \Rrightarrow \twoheadleftarrow \leftarrowtail \looparrowleft \leftrightharpoons \curvearrowleft \circlearrowleft \Lsh \upuparrows \upharpoonleft \downharpoonleft \multimap \leftrightsquigarrow \rightrightarrows \rightleftarrows \rightrightarrows \rightleftarrows \twoheadrightarrow \rightarrowtail \looparrowright \rightleftharpoons \curvearrowright \circlearrowright \Rsh \downdownarrows \upharpoonright \downharpoonright \rightsquigarrow \nleftarrow \nrightarrow \nLeftarrow \nRightarrow \nleftrightarrow \nLeftrightarrow \to \Swarrow \Searrow \Nwarrow \Nearrow \leftsquigarrow """], ["Miscellaneous symbols", 4, r"""\neg \infty \forall \wp \exists \bigstar \angle \partial \nexists \measuredangle \eth \emptyset \sphericalangle \clubsuit \varnothing \complement \diamondsuit \imath \Finv \triangledown \heartsuit \jmath \Game \spadesuit \ell \hbar \vartriangle \cdots \hslash \vdots \blacksquare \ldots \blacktriangle \ddots \sharp \prime \blacktriangledown \Im \flat \backprime \Re \natural \circledS \P \copyright \ss \circledR \S \yen \AA \checkmark \$ \iiint \iint \iint \oiiint"""] ] def run(state_machine): def get_n(n, l): part = [] for x in l: part.append(x) if len(part) == n: yield part part = [] yield part lines = [] for category, columns, syms in symbols: syms = sorted(syms.split()) lines.append("**%s**" % category) lines.append('') max_width = max(map(len, syms)) * 2 + 16 header = " " + (('=' * max_width) + ' ') * columns lines.append(header) for part in get_n(columns, syms): line = ( " " + " ".join( "{} ``{}``".format( sym if not sym.startswith("\\") else sym[1:] if (sym[1:] in mathtext.Parser._overunder_functions or sym[1:] in mathtext.Parser._function_names) else chr(mathtext.tex2uni[sym[1:]]), sym) .rjust(max_width) for sym in part)) lines.append(line) lines.append(header) lines.append('') state_machine.insert_input(lines, "Symbol table") return [] def math_symbol_table_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return run(state_machine) def setup(app): app.add_directive( 'math_symbol_table', math_symbol_table_directive, False, (0, 1, 0)) metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata if __name__ == "__main__": # Do some verification of the tables from matplotlib import _mathtext_data print("SYMBOLS NOT IN STIX:") all_symbols = {} for category, columns, syms in symbols: if category == "Standard Function Names": continue syms = syms.split() for sym in syms: if len(sym) > 1: all_symbols[sym[1:]] = None if sym[1:] not in _mathtext_data.tex2uni: print(sym) print("SYMBOLS NOT IN TABLE:") for sym in _mathtext_data.tex2uni: if sym not in all_symbols: print(sym)
e1a830a41af129cfd1cf64e69624d7050af241227ab92514d5ca8b64046520f3
"""Define text roles for GitHub * ghissue - Issue * ghpull - Pull Request * ghuser - User Adapted from bitbucket example here: https://bitbucket.org/birkenfeld/sphinx-contrib/src/tip/bitbucket/sphinxcontrib/bitbucket.py Authors ------- * Doug Hellmann * Min RK """ # # Original Copyright (c) 2010 Doug Hellmann. All rights reserved. # from docutils import nodes, utils from docutils.parsers.rst.roles import set_classes def make_link_node(rawtext, app, type, slug, options): """Create a link to a github resource. :param rawtext: Text being replaced with link node. :param app: Sphinx application context :param type: Link type (issues, changeset, etc.) :param slug: ID of the thing to link to :param options: Options dictionary passed to role func. """ try: base = app.config.github_project_url if not base: raise AttributeError if not base.endswith('/'): base += '/' except AttributeError as err: raise ValueError('github_project_url configuration value is not set (%s)' % str(err)) ref = base + type + '/' + slug + '/' set_classes(options) prefix = "#" if type == 'pull': prefix = "PR " + prefix node = nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref, **options) return node def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ try: issue_num = int(text) if issue_num <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( 'GitHub issue number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] app = inliner.document.settings.env.app if 'pull' in name.lower(): category = 'pull' elif 'issue' in name.lower(): category = 'issues' else: msg = inliner.reporter.error( 'GitHub roles include "ghpull" and "ghissue", ' '"%s" is invalid.' % name, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] node = make_link_node(rawtext, app, category, str(issue_num), options) return [node], [] def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub user. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ app = inliner.document.settings.env.app ref = 'https://www.github.com/' + text node = nodes.reference(rawtext, text, refuri=ref, **options) return [node], [] def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub commit. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :param rawtext: The entire markup snippet, with role. :param text: The text marked with the role. :param lineno: The line number where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ app = inliner.document.settings.env.app try: base = app.config.github_project_url if not base: raise AttributeError if not base.endswith('/'): base += '/' except AttributeError as err: raise ValueError('github_project_url configuration value is not set (%s)' % str(err)) ref = base + text node = nodes.reference(rawtext, text[:6], refuri=ref, **options) return [node], [] def setup(app): """Install the plugin. :param app: Sphinx application context. """ app.add_role('ghissue', ghissue_role) app.add_role('ghpull', ghissue_role) app.add_role('ghuser', ghuser_role) app.add_role('ghcommit', ghcommit_role) app.add_config_value('github_project_url', None, 'env') metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata
3468933c988b8a060761b5099c6352b8ebcf3c8bc787ba283c64f09545c1cf79
# Skip deprecated members def skip_deprecated(app, what, name, obj, skip, options): if skip: return skip skipped = {"matplotlib.colors": ["ColorConverter", "hex2color", "rgb2hex"]} skip_list = skipped.get(getattr(obj, "__module__", None)) if skip_list is not None: return getattr(obj, "__name__", None) in skip_list def setup(app): app.connect('autodoc-skip-member', skip_deprecated) metadata = {'parallel_read_safe': True, 'parallel_write_safe': True} return metadata
752b4b5f70465b297b3ea994582f06a9e32f60d4ef9054b3c978653098516fe8
import sys from unittest.mock import MagicMock class MyCairoCffi(MagicMock): __name__ = "cairocffi" def setup(app): sys.modules.update( cairocffi=MyCairoCffi(), ) return {'parallel_read_safe': True, 'parallel_write_safe': True}
1300cf82ee9ab3d49fd78063897d95b4ba30bdbd1721d6d4c11aa6552c442b37
""" Configuration for the order of gallery sections and examples. Paths are relative to the conf.py file. """ from sphinx_gallery.sorting import ExplicitOrder # Gallery sections shall be displayed in the following order. # Non-matching sections are appended. explicit_order_folders = [ '../examples/lines_bars_and_markers', '../examples/images_contours_and_fields', '../examples/subplots_axes_and_figures', '../examples/statistics', '../examples/pie_and_polar_charts', '../examples/text_labels_and_annotations', '../examples/pyplots', '../examples/color', '../examples/shapes_and_collections', '../examples/style_sheets', '../examples/axes_grid1', '../examples/axisartist', '../examples/showcase', '../tutorials/introductory', '../tutorials/intermediate', '../tutorials/advanced'] class MplExplicitOrder(ExplicitOrder): """ for use within the 'subsection_order' key""" def __call__(self, item): """Return a string determining the sort order.""" if item in self.ordered_list: return "{:04d}".format(self.ordered_list.index(item)) else: # ensure not explicitly listed items come last. return "zzz" + item # Subsection order: # Subsections are ordered by filename, unless they appear in the following # lists in which case the list order determines the order within the section. # Examples/tutorials that do not appear in a list will be appended. list_all = [ # **Tutorials** # introductory "usage", "pyplot", "sample_plots", "images", "lifecycle", "customizing", # intermediate "artists", "legend_guide", "color_cycle", "gridspec", "constrainedlayout_guide", "tight_layout_guide", # advanced # text "text_intro", "text_props", # colors "colors", # **Examples** # color "color_demo", # pies "pie_features", "pie_demo2", ] explicit_subsection_order = [item + ".py" for item in list_all] class MplExplicitSubOrder(object): """ for use within the 'within_subsection_order' key """ def __init__(self, src_dir): self.src_dir = src_dir # src_dir is unused here self.ordered_list = explicit_subsection_order def __call__(self, item): """Return a string determining the sort order.""" if item in self.ordered_list: return "{:04d}".format(self.ordered_list.index(item)) else: # ensure not explicitly listed items come last. return "zzz" + item # Provide the above classes for use in conf.py sectionorder = MplExplicitOrder(explicit_order_folders) subsectionorder = MplExplicitSubOrder
7701a333e901dd9d0a79636980f2973c00b0abc5f4c78c9b6c786698bd950242
r""" ************************* Text rendering With LaTeX ************************* Rendering text with LaTeX in Matplotlib. Matplotlib has the option to use LaTeX to manage all text layout. This option is available with the following backends: * Agg * PS * PDF The LaTeX option is activated by setting ``text.usetex : True`` in your rc settings. Text handling with matplotlib's LaTeX support is slower than matplotlib's very capable :doc:`mathtext </tutorials/text/mathtext>`, but is more flexible, since different LaTeX packages (font packages, math packages, etc.) can be used. The results can be striking, especially when you take care to use the same fonts in your figures as in the main document. Matplotlib's LaTeX support requires a working LaTeX_ installation, dvipng_ (which may be included with your LaTeX installation), and Ghostscript_ (GPL Ghostscript 9.0 or later is required). The executables for these external dependencies must all be located on your :envvar:`PATH`. There are a couple of options to mention, which can be changed using :doc:`rc settings </tutorials/introductory/customizing>`. Here is an example matplotlibrc file:: font.family : serif font.serif : Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman font.sans-serif : Helvetica, Avant Garde, Computer Modern Sans serif font.cursive : Zapf Chancery font.monospace : Courier, Computer Modern Typewriter text.usetex : true The first valid font in each family is the one that will be loaded. If the fonts are not specified, the Computer Modern fonts are used by default. All of the other fonts are Adobe fonts. Times and Palatino each have their own accompanying math fonts, while the other Adobe serif fonts make use of the Computer Modern math fonts. See the PSNFSS_ documentation for more details. To use LaTeX and select Helvetica as the default font, without editing matplotlibrc use:: from matplotlib import rc rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) ## for Palatino and other serif fonts use: #rc('font',**{'family':'serif','serif':['Palatino']}) rc('text', usetex=True) Here is the standard example, `tex_demo.py`: .. figure:: ../../gallery/text_labels_and_annotations/images/sphx_glr_tex_demo_001.png :target: ../../gallery/text_labels_and_annotations/tex_demo.html :align: center :scale: 50 TeX Demo Note that display math mode (``$$ e=mc^2 $$``) is not supported, but adding the command ``\displaystyle``, as in `tex_demo.py`, will produce the same results. .. note:: Certain characters require special escaping in TeX, such as:: # $ % & ~ _ ^ \ { } \( \) \[ \] Therefore, these characters will behave differently depending on the rcParam ``text.usetex`` flag. .. _usetex-unicode: usetex with unicode =================== It is also possible to use unicode strings with the LaTeX text manager, here is an example taken from `tex_demo.py`. The axis labels include Unicode text: .. figure:: ../../gallery/text_labels_and_annotations/images/sphx_glr_tex_demo_001.png :target: ../../gallery/text_labels_and_annotations/tex_demo.html :align: center :scale: 50 TeX Unicode Demo .. _usetex-postscript: Postscript options ================== In order to produce encapsulated postscript files that can be embedded in a new LaTeX document, the default behavior of matplotlib is to distill the output, which removes some postscript operators used by LaTeX that are illegal in an eps file. This step produces results which may be unacceptable to some users, because the text is coarsely rasterized and converted to bitmaps, which are not scalable like standard postscript, and the text is not searchable. One workaround is to set ``ps.distiller.res`` to a higher value (perhaps 6000) in your rc settings, which will produce larger files but may look better and scale reasonably. A better workaround, which requires Poppler_ or Xpdf_, can be activated by changing the ``ps.usedistiller`` rc setting to ``xpdf``. This alternative produces postscript without rasterizing text, so it scales properly, can be edited in Adobe Illustrator, and searched text in pdf documents. .. _usetex-hangups: Possible hangups ================ * On Windows, the :envvar:`PATH` environment variable may need to be modified to include the directories containing the latex, dvipng and ghostscript executables. See :ref:`environment-variables` and :ref:`setting-windows-environment-variables` for details. * Using MiKTeX with Computer Modern fonts, if you get odd \*Agg and PNG results, go to MiKTeX/Options and update your format files * On Ubuntu and Gentoo, the base texlive install does not ship with the type1cm package. You may need to install some of the extra packages to get all the goodies that come bundled with other latex distributions. * Some progress has been made so matplotlib uses the dvi files directly for text layout. This allows latex to be used for text layout with the pdf and svg backends, as well as the \*Agg and PS backends. In the future, a latex installation may be the only external dependency. .. _usetex-troubleshooting: Troubleshooting =============== * Try deleting your :file:`.matplotlib/tex.cache` directory. If you don't know where to find :file:`.matplotlib`, see :ref:`locating-matplotlib-config-dir`. * Make sure LaTeX, dvipng and ghostscript are each working and on your :envvar:`PATH`. * Make sure what you are trying to do is possible in a LaTeX document, that your LaTeX syntax is valid and that you are using raw strings if necessary to avoid unintended escape sequences. * Most problems reported on the mailing list have been cleared up by upgrading Ghostscript_. If possible, please try upgrading to the latest release before reporting problems to the list. * The ``text.latex.preamble`` rc setting is not officially supported. This option provides lots of flexibility, and lots of ways to cause problems. Please disable this option before reporting problems to the mailing list. * If you still need help, please see :ref:`reporting-problems` .. _LaTeX: http://www.tug.org .. _dvipng: http://www.nongnu.org/dvipng/ .. _Ghostscript: https://ghostscript.com/ .. _PSNFSS: http://www.ctan.org/tex-archive/macros/latex/required/psnfss/psnfss2e.pdf .. _Poppler: https://poppler.freedesktop.org/ .. _Xpdf: http://www.xpdfreader.com/ """
8d38298a33eee95b24ad0e5d830c177116ff3b7f09b12a4833cd02f5846d4f93
r""" Annotations =========== Annotating text with Matplotlib. .. contents:: Table of Contents :depth: 3 .. _annotations-tutorial: Basic annotation ---------------- The uses of the basic :func:`~matplotlib.pyplot.text` will place text at an arbitrary position on the Axes. A common use case of text is to annotate some feature of the plot, and the :func:`~matplotlib.Axes.annotate` method provides helper functionality to make annotations easy. In an annotation, there are two points to consider: the location being annotated represented by the argument ``xy`` and the location of the text ``xytext``. Both of these arguments are ``(x,y)`` tuples. .. figure:: ../../gallery/pyplots/images/sphx_glr_annotation_basic_001.png :target: ../../gallery/pyplots/annotation_basic.html :align: center :scale: 50 Annotation Basic In this example, both the ``xy`` (arrow tip) and ``xytext`` locations (text location) are in data coordinates. There are a variety of other coordinate systems one can choose -- you can specify the coordinate system of ``xy`` and ``xytext`` with one of the following strings for ``xycoords`` and ``textcoords`` (default is 'data') ==================== ==================================================== argument coordinate system ==================== ==================================================== 'figure points' points from the lower left corner of the figure 'figure pixels' pixels from the lower left corner of the figure 'figure fraction' 0,0 is lower left of figure and 1,1 is upper right 'axes points' points from lower left corner of axes 'axes pixels' pixels from lower left corner of axes 'axes fraction' 0,0 is lower left of axes and 1,1 is upper right 'data' use the axes data coordinate system ==================== ==================================================== For example to place the text coordinates in fractional axes coordinates, one could do:: ax.annotate('local max', xy=(3, 1), xycoords='data', xytext=(0.8, 0.95), textcoords='axes fraction', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='right', verticalalignment='top', ) For physical coordinate systems (points or pixels) the origin is the bottom-left of the figure or axes. Optionally, you can enable drawing of an arrow from the text to the annotated point by giving a dictionary of arrow properties in the optional keyword argument ``arrowprops``. ==================== ===================================================== ``arrowprops`` key description ==================== ===================================================== width the width of the arrow in points frac the fraction of the arrow length occupied by the head headwidth the width of the base of the arrow head in points shrink move the tip and base some percent away from the annotated point and text \*\*kwargs any key for :class:`matplotlib.patches.Polygon`, e.g., ``facecolor`` ==================== ===================================================== In the example below, the ``xy`` point is in native coordinates (``xycoords`` defaults to 'data'). For a polar axes, this is in (theta, radius) space. The text in this example is placed in the fractional figure coordinate system. :class:`matplotlib.text.Text` keyword args like ``horizontalalignment``, ``verticalalignment`` and ``fontsize`` are passed from `~matplotlib.Axes.annotate` to the ``Text`` instance. .. figure:: ../../gallery/pyplots/images/sphx_glr_annotation_polar_001.png :target: ../../gallery/pyplots/annotation_polar.html :align: center :scale: 50 Annotation Polar For more on all the wild and wonderful things you can do with annotations, including fancy arrows, see :ref:`plotting-guide-annotation` and :doc:`/gallery/text_labels_and_annotations/annotation_demo`. Do not proceed unless you have already read :ref:`annotations-tutorial`, :func:`~matplotlib.pyplot.text` and :func:`~matplotlib.pyplot.annotate`! .. _plotting-guide-annotation: Advanced Annotations -------------------- Annotating with Text with Box ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Let's start with a simple example. .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_text_arrow_001.png :target: ../../gallery/userdemo/annotate_text_arrow.html :align: center :scale: 50 Annotate Text Arrow The :func:`~matplotlib.pyplot.text` function in the pyplot module (or text method of the Axes class) takes bbox keyword argument, and when given, a box around the text is drawn. :: bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="cyan", ec="b", lw=2) t = ax.text(0, 0, "Direction", ha="center", va="center", rotation=45, size=15, bbox=bbox_props) The patch object associated with the text can be accessed by:: bb = t.get_bbox_patch() The return value is an instance of FancyBboxPatch and the patch properties like facecolor, edgewidth, etc. can be accessed and modified as usual. To change the shape of the box, use the *set_boxstyle* method. :: bb.set_boxstyle("rarrow", pad=0.6) The arguments are the name of the box style with its attributes as keyword arguments. Currently, following box styles are implemented. ========== ============== ========================== Class Name Attrs ========== ============== ========================== Circle ``circle`` pad=0.3 DArrow ``darrow`` pad=0.3 LArrow ``larrow`` pad=0.3 RArrow ``rarrow`` pad=0.3 Round ``round`` pad=0.3,rounding_size=None Round4 ``round4`` pad=0.3,rounding_size=None Roundtooth ``roundtooth`` pad=0.3,tooth_size=None Sawtooth ``sawtooth`` pad=0.3,tooth_size=None Square ``square`` pad=0.3 ========== ============== ========================== .. figure:: ../../gallery/shapes_and_collections/images/sphx_glr_fancybox_demo_001.png :target: ../../gallery/shapes_and_collections/fancybox_demo.html :align: center :scale: 50 Fancybox Demo Note that the attribute arguments can be specified within the style name with separating comma (this form can be used as "boxstyle" value of bbox argument when initializing the text instance) :: bb.set_boxstyle("rarrow,pad=0.6") Annotating with Arrow ~~~~~~~~~~~~~~~~~~~~~ The :func:`~matplotlib.pyplot.annotate` function in the pyplot module (or annotate method of the Axes class) is used to draw an arrow connecting two points on the plot. :: ax.annotate("Annotation", xy=(x1, y1), xycoords='data', xytext=(x2, y2), textcoords='offset points', ) This annotates a point at ``xy`` in the given coordinate (``xycoords``) with the text at ``xytext`` given in ``textcoords``. Often, the annotated point is specified in the *data* coordinate and the annotating text in *offset points*. See :func:`~matplotlib.pyplot.annotate` for available coordinate systems. An arrow connecting two points (xy & xytext) can be optionally drawn by specifying the ``arrowprops`` argument. To draw only an arrow, use empty string as the first argument. :: ax.annotate("", xy=(0.2, 0.2), xycoords='data', xytext=(0.8, 0.8), textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3"), ) .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple01_001.png :target: ../../gallery/userdemo/annotate_simple01.html :align: center :scale: 50 Annotate Simple01 The arrow drawing takes a few steps. 1. a connecting path between two points are created. This is controlled by ``connectionstyle`` key value. 2. If patch object is given (*patchA* & *patchB*), the path is clipped to avoid the patch. 3. The path is further shrunk by given amount of pixels (*shrinkA* & *shrinkB*) 4. The path is transmuted to arrow patch, which is controlled by the ``arrowstyle`` key value. .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_explain_001.png :target: ../../gallery/userdemo/annotate_explain.html :align: center :scale: 50 Annotate Explain The creation of the connecting path between two points is controlled by ``connectionstyle`` key and the following styles are available. ========== ============================================= Name Attrs ========== ============================================= ``angle`` angleA=90,angleB=0,rad=0.0 ``angle3`` angleA=90,angleB=0 ``arc`` angleA=0,angleB=0,armA=None,armB=None,rad=0.0 ``arc3`` rad=0.0 ``bar`` armA=0.0,armB=0.0,fraction=0.3,angle=None ========== ============================================= Note that "3" in ``angle3`` and ``arc3`` is meant to indicate that the resulting path is a quadratic spline segment (three control points). As will be discussed below, some arrow style options can only be used when the connecting path is a quadratic spline. The behavior of each connection style is (limitedly) demonstrated in the example below. (Warning : The behavior of the ``bar`` style is currently not well defined, it may be changed in the future). .. figure:: ../../gallery/userdemo/images/sphx_glr_connectionstyle_demo_001.png :target: ../../gallery/userdemo/connectionstyle_demo.html :align: center :scale: 50 Connectionstyle Demo The connecting path (after clipping and shrinking) is then mutated to an arrow patch, according to the given ``arrowstyle``. ========== ============================================= Name Attrs ========== ============================================= ``-`` None ``->`` head_length=0.4,head_width=0.2 ``-[`` widthB=1.0,lengthB=0.2,angleB=None ``|-|`` widthA=1.0,widthB=1.0 ``-|>`` head_length=0.4,head_width=0.2 ``<-`` head_length=0.4,head_width=0.2 ``<->`` head_length=0.4,head_width=0.2 ``<|-`` head_length=0.4,head_width=0.2 ``<|-|>`` head_length=0.4,head_width=0.2 ``fancy`` head_length=0.4,head_width=0.4,tail_width=0.4 ``simple`` head_length=0.5,head_width=0.5,tail_width=0.2 ``wedge`` tail_width=0.3,shrink_factor=0.5 ========== ============================================= .. figure:: ../../gallery/text_labels_and_annotations/images/sphx_glr_fancyarrow_demo_001.png :target: ../../gallery/text_labels_and_annotations/fancyarrow_demo.html :align: center :scale: 50 Fancyarrow Demo Some arrowstyles only work with connection styles that generate a quadratic-spline segment. They are ``fancy``, ``simple``, and ``wedge``. For these arrow styles, you must use the "angle3" or "arc3" connection style. If the annotation string is given, the patchA is set to the bbox patch of the text by default. .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple02_001.png :target: ../../gallery/userdemo/annotate_simple02.html :align: center :scale: 50 Annotate Simple02 As in the text command, a box around the text can be drawn using the ``bbox`` argument. .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple03_001.png :target: ../../gallery/userdemo/annotate_simple03.html :align: center :scale: 50 Annotate Simple03 By default, the starting point is set to the center of the text extent. This can be adjusted with ``relpos`` key value. The values are normalized to the extent of the text. For example, (0,0) means lower-left corner and (1,1) means top-right. .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple04_001.png :target: ../../gallery/userdemo/annotate_simple04.html :align: center :scale: 50 Annotate Simple04 Placing Artist at the anchored location of the Axes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are classes of artists that can be placed at an anchored location in the Axes. A common example is the legend. This type of artist can be created by using the OffsetBox class. A few predefined classes are available in ``mpl_toolkits.axes_grid1.anchored_artists`` others in ``matplotlib.offsetbox`` :: from matplotlib.offsetbox import AnchoredText at = AnchoredText("Figure 1a", prop=dict(size=15), frameon=True, loc='upper left', ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at) .. figure:: ../../gallery/userdemo/images/sphx_glr_anchored_box01_001.png :target: ../../gallery/userdemo/anchored_box01.html :align: center :scale: 50 Anchored Box01 The *loc* keyword has same meaning as in the legend command. A simple application is when the size of the artist (or collection of artists) is known in pixel size during the time of creation. For example, If you want to draw a circle with fixed size of 20 pixel x 20 pixel (radius = 10 pixel), you can utilize ``AnchoredDrawingArea``. The instance is created with a size of the drawing area (in pixels), and arbitrary artists can added to the drawing area. Note that the extents of the artists that are added to the drawing area are not related to the placement of the drawing area itself. Only the initial size matters. :: from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea ada = AnchoredDrawingArea(20, 20, 0, 0, loc='upper right', pad=0., frameon=False) p1 = Circle((10, 10), 10) ada.drawing_area.add_artist(p1) p2 = Circle((30, 10), 5, fc="r") ada.drawing_area.add_artist(p2) The artists that are added to the drawing area should not have a transform set (it will be overridden) and the dimensions of those artists are interpreted as a pixel coordinate, i.e., the radius of the circles in above example are 10 pixels and 5 pixels, respectively. .. figure:: ../../gallery/userdemo/images/sphx_glr_anchored_box02_001.png :target: ../../gallery/userdemo/anchored_box02.html :align: center :scale: 50 Anchored Box02 Sometimes, you want your artists to scale with the data coordinate (or coordinates other than canvas pixels). You can use ``AnchoredAuxTransformBox`` class. This is similar to ``AnchoredDrawingArea`` except that the extent of the artist is determined during the drawing time respecting the specified transform. :: from mpl_toolkits.axes_grid1.anchored_artists import AnchoredAuxTransformBox box = AnchoredAuxTransformBox(ax.transData, loc='upper left') el = Ellipse((0,0), width=0.1, height=0.4, angle=30) # in data coordinates! box.drawing_area.add_artist(el) The ellipse in the above example will have width and height corresponding to 0.1 and 0.4 in data coordinates and will be automatically scaled when the view limits of the axes change. .. figure:: ../../gallery/userdemo/images/sphx_glr_anchored_box03_001.png :target: ../../gallery/userdemo/anchored_box03.html :align: center :scale: 50 Anchored Box03 As in the legend, the bbox_to_anchor argument can be set. Using the HPacker and VPacker, you can have an arrangement(?) of artist as in the legend (as a matter of fact, this is how the legend is created). .. figure:: ../../gallery/userdemo/images/sphx_glr_anchored_box04_001.png :target: ../../gallery/userdemo/anchored_box04.html :align: center :scale: 50 Anchored Box04 Note that unlike the legend, the ``bbox_transform`` is set to IdentityTransform by default. Using Complex Coordinates with Annotations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Annotation in matplotlib supports several types of coordinates as described in :ref:`annotations-tutorial`. For an advanced user who wants more control, it supports a few other options. 1. :class:`~matplotlib.transforms.Transform` instance. For example, :: ax.annotate("Test", xy=(0.5, 0.5), xycoords=ax.transAxes) is identical to :: ax.annotate("Test", xy=(0.5, 0.5), xycoords="axes fraction") With this, you can annotate a point in other axes. :: ax1, ax2 = subplot(121), subplot(122) ax2.annotate("Test", xy=(0.5, 0.5), xycoords=ax1.transData, xytext=(0.5, 0.5), textcoords=ax2.transData, arrowprops=dict(arrowstyle="->")) 2. :class:`~matplotlib.artist.Artist` instance. The xy value (or xytext) is interpreted as a fractional coordinate of the bbox (return value of *get_window_extent*) of the artist. :: an1 = ax.annotate("Test 1", xy=(0.5, 0.5), xycoords="data", va="center", ha="center", bbox=dict(boxstyle="round", fc="w")) an2 = ax.annotate("Test 2", xy=(1, 0.5), xycoords=an1, # (1,0.5) of the an1's bbox xytext=(30,0), textcoords="offset points", va="center", ha="left", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="->")) .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple_coord01_001.png :target: ../../gallery/userdemo/annotate_simple_coord01.html :align: center :scale: 50 Annotation with Simple Coordinates Note that it is your responsibility that the extent of the coordinate artist (*an1* in above example) is determined before *an2* gets drawn. In most cases, it means that *an2* needs to be drawn later than *an1*. 3. A callable object that returns an instance of either :class:`~matplotlib.transforms.BboxBase` or :class:`~matplotlib.transforms.Transform`. If a transform is returned, it is the same as 1 and if a bbox is returned, it is the same as 2. The callable object should take a single argument of the renderer instance. For example, the following two commands give identical results :: an2 = ax.annotate("Test 2", xy=(1, 0.5), xycoords=an1, xytext=(30,0), textcoords="offset points") an2 = ax.annotate("Test 2", xy=(1, 0.5), xycoords=an1.get_window_extent, xytext=(30,0), textcoords="offset points") 4. A tuple of two coordinate specifications. The first item is for the x-coordinate and the second is for the y-coordinate. For example, :: annotate("Test", xy=(0.5, 1), xycoords=("data", "axes fraction")) 0.5 is in data coordinates, and 1 is in normalized axes coordinates. You may use an artist or transform as with a tuple. For example, .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple_coord02_001.png :target: ../../gallery/userdemo/annotate_simple_coord02.html :align: center :scale: 50 Annotation with Simple Coordinates 2 5. Sometimes, you want your annotation with some "offset points", not from the annotated point but from some other point. :class:`~matplotlib.text.OffsetFrom` is a helper class for such cases. .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple_coord03_001.png :target: ../../gallery/userdemo/annotate_simple_coord03.html :align: center :scale: 50 Annotation with Simple Coordinates 3 You may take a look at this example :doc:`/gallery/text_labels_and_annotations/annotation_demo`. Using ConnectionPatch ~~~~~~~~~~~~~~~~~~~~~ The ConnectionPatch is like an annotation without text. While the annotate function is recommended in most situations, the ConnectionPatch is useful when you want to connect points in different axes. :: from matplotlib.patches import ConnectionPatch xy = (0.2, 0.2) con = ConnectionPatch(xyA=xy, xyB=xy, coordsA="data", coordsB="data", axesA=ax1, axesB=ax2) ax2.add_artist(con) The above code connects point xy in the data coordinates of ``ax1`` to point xy in the data coordinates of ``ax2``. Here is a simple example. .. figure:: ../../gallery/userdemo/images/sphx_glr_connect_simple01_001.png :target: ../../gallery/userdemo/connect_simple01.html :align: center :scale: 50 Connect Simple01 While the ConnectionPatch instance can be added to any axes, you may want to add it to the axes that is latest in drawing order to prevent overlap by other axes. Advanced Topics --------------- Zoom effect between Axes ~~~~~~~~~~~~~~~~~~~~~~~~ ``mpl_toolkits.axes_grid1.inset_locator`` defines some patch classes useful for interconnecting two axes. Understanding the code requires some knowledge of how mpl's transform works. But, utilizing it will be straight forward. .. figure:: ../../gallery/subplots_axes_and_figures/images/sphx_glr_axes_zoom_effect_001.png :target: ../../gallery/subplots_axes_and_figures/axes_zoom_effect.html :align: center :scale: 50 Axes Zoom Effect Define Custom BoxStyle ~~~~~~~~~~~~~~~~~~~~~~ You can use a custom box style. The value for the ``boxstyle`` can be a callable object in the following forms.:: def __call__(self, x0, y0, width, height, mutation_size, aspect_ratio=1.): ''' Given the location and size of the box, return the path of the box around it. - *x0*, *y0*, *width*, *height* : location and size of the box - *mutation_size* : a reference scale for the mutation. - *aspect_ratio* : aspect-ratio for the mutation. ''' path = ... return path Here is a complete example. .. figure:: ../../gallery/userdemo/images/sphx_glr_custom_boxstyle01_001.png :target: ../../gallery/userdemo/custom_boxstyle01.html :align: center :scale: 50 Custom Boxstyle01 However, it is recommended that you derive from the matplotlib.patches.BoxStyle._Base as demonstrated below. .. figure:: ../../gallery/userdemo/images/sphx_glr_custom_boxstyle02_001.png :target: ../../gallery/userdemo/custom_boxstyle02.html :align: center :scale: 50 Custom Boxstyle02 Similarly, you can define a custom ConnectionStyle and a custom ArrowStyle. See the source code of ``lib/matplotlib/patches.py`` and check how each style class is defined. """
711b109e2b77b11b8ef9b836b88d24c746dbdf237fe9518012444cda351c7b21
""" ======================== Text in Matplotlib Plots ======================== Introduction to plotting and working with text in Matplotlib. Matplotlib has extensive text support, including support for mathematical expressions, truetype support for raster and vector outputs, newline separated text with arbitrary rotations, and unicode support. Because it embeds fonts directly in output documents, e.g., for postscript or PDF, what you see on the screen is what you get in the hardcopy. `FreeType <https://www.freetype.org/>`_ support produces very nice, antialiased fonts, that look good even at small raster sizes. Matplotlib includes its own :mod:`matplotlib.font_manager` (thanks to Paul Barrett), which implements a cross platform, `W3C <http://www.w3.org/>` compliant font finding algorithm. The user has a great deal of control over text properties (font size, font weight, text location and color, etc.) with sensible defaults set in the :doc:`rc file </tutorials/introductory/customizing>`. And significantly, for those interested in mathematical or scientific figures, Matplotlib implements a large number of TeX math symbols and commands, supporting :doc:`mathematical expressions </tutorials/text/mathtext>` anywhere in your figure. Basic text commands =================== The following commands are used to create text in the pyplot interface and the object-oriented API: =================== =================== ====================================== `.pyplot` API OO API description =================== =================== ====================================== `~.pyplot.text` `~.Axes.text` Add text at an arbitrary location of the `~matplotlib.axes.Axes`. `~.pyplot.annotate` `~.Axes.annotate` Add an annotation, with an optional arrow, at an arbitrary location of the `~matplotlib.axes.Axes`. `~.pyplot.xlabel` `~.Axes.set_xlabel` Add a label to the `~matplotlib.axes.Axes`\\'s x-axis. `~.pyplot.ylabel` `~.Axes.set_ylabel` Add a label to the `~matplotlib.axes.Axes`\\'s y-axis. `~.pyplot.title` `~.Axes.set_title` Add a title to the `~matplotlib.axes.Axes`. `~.pyplot.figtext` `~.Figure.text` Add text at an arbitrary location of the `.Figure`. `~.pyplot.suptitle` `~.Figure.suptitle` Add a title to the `.Figure`. =================== =================== ====================================== All of these functions create and return a `.Text` instance, which can be configured with a variety of font and other properties. The example below shows all of these commands in action, and more detail is provided in the sections that follow. """ import matplotlib import matplotlib.pyplot as plt fig = plt.figure() fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold') ax = fig.add_subplot(111) fig.subplots_adjust(top=0.85) ax.set_title('axes title') ax.set_xlabel('xlabel') ax.set_ylabel('ylabel') ax.text(3, 8, 'boxed italics text in data coords', style='italic', bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10}) ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15) ax.text(3, 2, 'unicode: Institut für Festkörperphysik') ax.text(0.95, 0.01, 'colored text in axes coords', verticalalignment='bottom', horizontalalignment='right', transform=ax.transAxes, color='green', fontsize=15) ax.plot([2], [1], 'o') ax.annotate('annotate', xy=(2, 1), xytext=(3, 4), arrowprops=dict(facecolor='black', shrink=0.05)) ax.axis([0, 10, 0, 10]) plt.show() ############################################################################### # Labels for x- and y-axis # ======================== # # Specifying the labels for the x- and y-axis is straightforward, via the # `~matplotlib.axes.Axes.set_xlabel` and `~matplotlib.axes.Axes.set_ylabel` # methods. import matplotlib.pyplot as plt import numpy as np x1 = np.linspace(0.0, 5.0, 100) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) fig, ax = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1) ax.set_xlabel('time [s]') ax.set_ylabel('Damped oscillation [V]') plt.show() ############################################################################### # The x- and y-labels are automatically placed so that they clear the x- and # y-ticklabels. Compare the plot below with that above, and note the y-label # is to the left of the one above. fig, ax = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1*10000) ax.set_xlabel('time [s]') ax.set_ylabel('Damped oscillation [V]') plt.show() ############################################################################### # If you want to move the labels, you can specify the *labelpad* keyword # argument, where the value is points (1/72", the same unit used to specify # fontsizes). fig, ax = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1*10000) ax.set_xlabel('time [s]') ax.set_ylabel('Damped oscillation [V]', labelpad=18) plt.show() ############################################################################### # Or, the labels accept all the `.Text` keyword arguments, including # *position*, via which we can manually specify the label positions. Here we # put the xlabel to the far left of the axis. Note, that the y-coordinate of # this position has no effect - to adjust the y-position we need to use the # *labelpad* kwarg. fig, ax = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1) ax.set_xlabel('time [s]', position=(0., 1e6), horizontalalignment='left') ax.set_ylabel('Damped oscillation [V]') plt.show() ############################################################################## # All the labelling in this tutorial can be changed by manipulating the # `matplotlib.font_manager.FontProperties` method, or by named kwargs to # `~matplotlib.axes.Axes.set_xlabel` from matplotlib.font_manager import FontProperties font = FontProperties() font.set_family('serif') font.set_name('Times New Roman') font.set_style('italic') fig, ax = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1) ax.set_xlabel('time [s]', fontsize='large', fontweight='bold') ax.set_ylabel('Damped oscillation [V]', fontproperties=font) plt.show() ############################################################################## # Finally, we can use native TeX rendering in all text objects and have # multiple lines: fig, ax = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.2, left=0.2) ax.plot(x1, np.cumsum(y1**2)) ax.set_xlabel('time [s] \n This was a long experiment') ax.set_ylabel(r'$\int\ Y^2\ dt\ \ [V^2 s]$') plt.show() ############################################################################## # Titles # ====== # # Subplot titles are set in much the same way as labels, but there is # the *loc* keyword arguments that can change the position and justification # from the default value of ``loc=center``. fig, axs = plt.subplots(3, 1, figsize=(5, 6), tight_layout=True) locs = ['center', 'left', 'right'] for ax, loc in zip(axs, locs): ax.plot(x1, y1) ax.set_title('Title with loc at '+loc, loc=loc) plt.show() ############################################################################## # Vertical spacing for titles is controlled via :rc:`axes.titlepad`, which # defaults to 5 points. Setting to a different value moves the title. fig, ax = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(top=0.8) ax.plot(x1, y1) ax.set_title('Vertically offset title', pad=30) plt.show() ############################################################################## # Ticks and ticklabels # ==================== # # Placing ticks and ticklabels is a very tricky aspect of making a figure. # Matplotlib does the best it can automatically, but it also offers a very # flexible framework for determining the choices for tick locations, and # how they are labelled. # # Terminology # ~~~~~~~~~~~ # # *Axes* have an `matplotlib.axis` object for the ``ax.xaxis`` # and ``ax.yaxis`` that # contain the information about how the labels in the axis are laid out. # # The axis API is explained in detail in the documentation to # `~matplotlib.axis`. # # An Axis object has major and minor ticks. The Axis has a # `matplotlib.xaxis.set_major_locator` and # `matplotlib.xaxis.set_minor_locator` methods that use the data being plotted # to determine # the location of major and minor ticks. There are also # `matplotlib.xaxis.set_major_formatter` and # `matplotlib.xaxis.set_minor_formatters` methods that format the tick labels. # # Simple ticks # ~~~~~~~~~~~~ # # It often is convenient to simply define the # tick values, and sometimes the tick labels, overriding the default # locators and formatters. This is discouraged because it breaks itneractive # navigation of the plot. It also can reset the axis limits: note that # the second plot has the ticks we asked for, including ones that are # well outside the automatic view limits. fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) axs[0].plot(x1, y1) axs[1].plot(x1, y1) axs[1].xaxis.set_ticks(np.arange(0., 8.1, 2.)) plt.show() ############################################################################# # We can of course fix this after the fact, but it does highlight a # weakness of hard-coding the ticks. This example also changes the format # of the ticks: fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) axs[0].plot(x1, y1) axs[1].plot(x1, y1) ticks = np.arange(0., 8.1, 2.) # list comprehension to get all tick labels... tickla = ['%1.2f' % tick for tick in ticks] axs[1].xaxis.set_ticks(ticks) axs[1].xaxis.set_ticklabels(tickla) axs[1].set_xlim(axs[0].get_xlim()) plt.show() ############################################################################# # Tick Locators and Formatters # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Instead of making a list of all the tickalbels, we could have # used a `matplotlib.ticker.FormatStrFormatter` and passed it to the # ``ax.xaxis`` fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) axs[0].plot(x1, y1) axs[1].plot(x1, y1) ticks = np.arange(0., 8.1, 2.) # list comprehension to get all tick labels... formatter = matplotlib.ticker.StrMethodFormatter('{x:1.1f}') axs[1].xaxis.set_ticks(ticks) axs[1].xaxis.set_major_formatter(formatter) axs[1].set_xlim(axs[0].get_xlim()) plt.show() ############################################################################# # And of course we could have used a non-default locator to set the # tick locations. Note we still pass in the tick values, but the # x-limit fix used above is *not* needed. fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True) axs[0].plot(x1, y1) axs[1].plot(x1, y1) formatter = matplotlib.ticker.FormatStrFormatter('%1.1f') locator = matplotlib.ticker.FixedLocator(ticks) axs[1].xaxis.set_major_locator(locator) axs[1].xaxis.set_major_formatter(formatter) plt.show() ############################################################################# # The default formatter is the `matplotlib.ticker.MaxNLocator` called as # ``ticker.MaxNLocator(self, nbins='auto', steps=[1, 2, 2.5, 5, 10])`` # The *steps* keyword contains a list of multiples that can be used for # tick values. i.e. in this case, 2, 4, 6 would be acceptable ticks, # as would 20, 40, 60 or 0.2, 0.4, 0.6. However, 3, 6, 9 would not be # acceptable because 3 doesn't appear in the list of steps. # # ``nbins=auto`` uses an algorithm to determine how many ticks will # be acceptable based on how long the axis is. The fontsize of the # ticklabel is taken into account, but the length of the tick string # is not (because its not yet known.) In the bottom row, the # ticklabels are quite large, so we set ``nbins=4`` to make the # labels fit in the right-hand plot. fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True) axs = axs.flatten() for n, ax in enumerate(axs): ax.plot(x1*10., y1) formatter = matplotlib.ticker.FormatStrFormatter('%1.1f') locator = matplotlib.ticker.MaxNLocator(nbins='auto', steps=[1, 4, 10]) axs[1].xaxis.set_major_locator(locator) axs[1].xaxis.set_major_formatter(formatter) formatter = matplotlib.ticker.FormatStrFormatter('%1.5f') locator = matplotlib.ticker.AutoLocator() axs[2].xaxis.set_major_formatter(formatter) axs[2].xaxis.set_major_locator(locator) formatter = matplotlib.ticker.FormatStrFormatter('%1.5f') locator = matplotlib.ticker.MaxNLocator(nbins=4) axs[3].xaxis.set_major_formatter(formatter) axs[3].xaxis.set_major_locator(locator) plt.show() ############################################################################## # Finally, we can specify functions for the formatter using # `matplotlib.ticker.FuncFormatter`. def formatoddticks(x, pos): """Format odd tick positions """ if x % 2: return '%1.2f' % x else: return '' fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True) ax.plot(x1, y1) formatter = matplotlib.ticker.FuncFormatter(formatoddticks) locator = matplotlib.ticker.MaxNLocator(nbins=6) ax.xaxis.set_major_formatter(formatter) ax.xaxis.set_major_locator(locator) plt.show() ############################################################################## # Dateticks # ~~~~~~~~~ # # Matplotlib can accept `datetime.datetime` and `numpy.datetime64` # objects as plotting arguments. Dates and times require special # formatting, which can often benefit from manual intervention. In # order to help, dates have special Locators and Formatters, # defined in the `matplotlib.dates` module. # # A simple example is as follows. Note how we have to rotate the # tick labels so that they don't over-run each other. import datetime fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True) base = datetime.datetime(2017, 1, 1, 0, 0, 1) time = [base + datetime.timedelta(days=x) for x in range(len(y1))] ax.plot(time, y1) ax.tick_params(axis='x', rotation=70) plt.show() ############################################################################## # We can pass a format # to `matplotlib.dates.DateFormatter`. Also note that the 29th and the # next month are very close together. We can fix this by using the # `dates.DayLocator` class, which allows us to specify a list of days of the # month to use. Similar formatters are listed in the `matplotlib.dates` module. import matplotlib.dates as mdates locator = mdates.DayLocator(bymonthday=[1, 15]) formatter = mdates.DateFormatter('%b %d') fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) ax.plot(time, y1) ax.tick_params(axis='x', rotation=70) plt.show() ############################################################################## # Legends and Annotations # ======================= # # - Legends: :doc:`/tutorials/intermediate/legend_guide` # - Annotations: :doc:`/tutorials/text/annotations` #
b379eb6d0926e7742ef4d83e8e272b3c4f216cc112a5e8b17157048bd21dc92a
r""" ********************************* Typesetting With XeLaTeX/LuaLaTeX ********************************* How to typeset text with the ``pgf`` backend in Matplotlib. Using the ``pgf`` backend, matplotlib can export figures as pgf drawing commands that can be processed with pdflatex, xelatex or lualatex. XeLaTeX and LuaLaTeX have full unicode support and can use any font that is installed in the operating system, making use of advanced typographic features of OpenType, AAT and Graphite. Pgf pictures created by ``plt.savefig('figure.pgf')`` can be embedded as raw commands in LaTeX documents. Figures can also be directly compiled and saved to PDF with ``plt.savefig('figure.pdf')`` by either switching to the backend .. code-block:: python matplotlib.use('pgf') or registering it for handling pdf output .. code-block:: python from matplotlib.backends.backend_pgf import FigureCanvasPgf matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf) The second method allows you to keep using regular interactive backends and to save xelatex, lualatex or pdflatex compiled PDF files from the graphical user interface. Matplotlib's pgf support requires a recent LaTeX_ installation that includes the TikZ/PGF packages (such as TeXLive_), preferably with XeLaTeX or LuaLaTeX installed. If either pdftocairo or ghostscript is present on your system, figures can optionally be saved to PNG images as well. The executables for all applications must be located on your :envvar:`PATH`. Rc parameters that control the behavior of the pgf backend: ================= ===================================================== Parameter Documentation ================= ===================================================== pgf.preamble Lines to be included in the LaTeX preamble pgf.rcfonts Setup fonts from rc params using the fontspec package pgf.texsystem Either "xelatex" (default), "lualatex" or "pdflatex" ================= ===================================================== .. note:: TeX defines a set of special characters, such as:: # $ % & ~ _ ^ \ { } Generally, these characters must be escaped correctly. For convenience, some characters (_,^,%) are automatically escaped outside of math environments. .. _pgf-rcfonts: Multi-Page PDF Files ==================== The pgf backend also supports multipage pdf files using ``PdfPages`` .. code-block:: python from matplotlib.backends.backend_pgf import PdfPages import matplotlib.pyplot as plt with PdfPages('multipage.pdf', metadata={'author': 'Me'}) as pdf: fig1, ax1 = plt.subplots() ax1.plot([1, 5, 3]) pdf.savefig(fig1) fig2, ax2 = plt.subplots() ax2.plot([1, 5, 3]) pdf.savefig(fig2) Font specification ================== The fonts used for obtaining the size of text elements or when compiling figures to PDF are usually defined in the matplotlib rc parameters. You can also use the LaTeX default Computer Modern fonts by clearing the lists for ``font.serif``, ``font.sans-serif`` or ``font.monospace``. Please note that the glyph coverage of these fonts is very limited. If you want to keep the Computer Modern font face but require extended unicode support, consider installing the `Computer Modern Unicode <https://sourceforge.net/projects/cm-unicode/>`_ fonts *CMU Serif*, *CMU Sans Serif*, etc. When saving to ``.pgf``, the font configuration matplotlib used for the layout of the figure is included in the header of the text file. .. literalinclude:: ../../gallery/userdemo/pgf_fonts.py :end-before: plt.savefig .. _pgf-preamble: Custom preamble =============== Full customization is possible by adding your own commands to the preamble. Use the ``pgf.preamble`` parameter if you want to configure the math fonts, using ``unicode-math`` for example, or for loading additional packages. Also, if you want to do the font configuration yourself instead of using the fonts specified in the rc parameters, make sure to disable ``pgf.rcfonts``. .. only:: html .. literalinclude:: ../../gallery/userdemo/pgf_preamble_sgskip.py :end-before: plt.savefig .. only:: latex .. literalinclude:: ../../gallery/userdemo/pgf_preamble_sgskip.py :end-before: import matplotlib.pyplot as plt .. _pgf-texsystem: Choosing the TeX system ======================= The TeX system to be used by matplotlib is chosen by the ``pgf.texsystem`` parameter. Possible values are ``'xelatex'`` (default), ``'lualatex'`` and ``'pdflatex'``. Please note that when selecting pdflatex the fonts and unicode handling must be configured in the preamble. .. literalinclude:: ../../gallery/userdemo/pgf_texsystem.py :end-before: plt.savefig .. _pgf-troubleshooting: Troubleshooting =============== * Please note that the TeX packages found in some Linux distributions and MiKTeX installations are dramatically outdated. Make sure to update your package catalog and upgrade or install a recent TeX distribution. * On Windows, the :envvar:`PATH` environment variable may need to be modified to include the directories containing the latex, dvipng and ghostscript executables. See :ref:`environment-variables` and :ref:`setting-windows-environment-variables` for details. * A limitation on Windows causes the backend to keep file handles that have been opened by your application open. As a result, it may not be possible to delete the corresponding files until the application closes (see `#1324 <https://github.com/matplotlib/matplotlib/issues/1324>`_). * Sometimes the font rendering in figures that are saved to png images is very bad. This happens when the pdftocairo tool is not available and ghostscript is used for the pdf to png conversion. * Make sure what you are trying to do is possible in a LaTeX document, that your LaTeX syntax is valid and that you are using raw strings if necessary to avoid unintended escape sequences. * The ``pgf.preamble`` rc setting provides lots of flexibility, and lots of ways to cause problems. When experiencing problems, try to minimalize or disable the custom preamble. * Configuring an ``unicode-math`` environment can be a bit tricky. The TeXLive distribution for example provides a set of math fonts which are usually not installed system-wide. XeTeX, unlike LuaLatex, cannot find these fonts by their name, which is why you might have to specify ``\setmathfont{xits-math.otf}`` instead of ``\setmathfont{XITS Math}`` or alternatively make the fonts available to your OS. See this `tex.stackexchange.com question <http://tex.stackexchange.com/questions/43642>`_ for more details. * If the font configuration used by matplotlib differs from the font setting in yout LaTeX document, the alignment of text elements in imported figures may be off. Check the header of your ``.pgf`` file if you are unsure about the fonts matplotlib used for the layout. * Vector images and hence ``.pgf`` files can become bloated if there are a lot of objects in the graph. This can be the case for image processing or very big scatter graphs. In an extreme case this can cause TeX to run out of memory: "TeX capacity exceeded, sorry" You can configure latex to increase the amount of memory available to generate the ``.pdf`` image as discussed on `tex.stackexchange.com <http://tex.stackexchange.com/questions/7953>`_. Another way would be to "rasterize" parts of the graph causing problems using either the ``rasterized=True`` keyword, or ``.set_rasterized(True)`` as per :doc:`this example </gallery/misc/rasterization_demo>`. * If you still need help, please see :ref:`reporting-problems` .. _LaTeX: http://www.tug.org .. _TeXLive: http://www.tug.org/texlive/ """
ec52a2e760e5e351e88e3c2cfd79056228d60b23b1e78b170b23b1bf1c59d496
""" ============================ Text properties and layout ============================ Controlling properties of text and its layout with Matplotlib. The :class:`matplotlib.text.Text` instances have a variety of properties which can be configured via keyword arguments to the text commands (e.g., :func:`~matplotlib.pyplot.title`, :func:`~matplotlib.pyplot.xlabel` and :func:`~matplotlib.pyplot.text`). ========================== ====================================================================================================================== Property Value Type ========================== ====================================================================================================================== alpha `float` backgroundcolor any matplotlib :doc:`color </tutorials/colors/colors>` bbox `~matplotlib.patches.Rectangle` prop dict plus key ``'pad'`` which is a pad in points clip_box a matplotlib.transform.Bbox instance clip_on bool clip_path a `~matplotlib.path.Path` instance and a `~matplotlib.transforms.Transform` instance, a `~matplotlib.patches.Patch` color any matplotlib :doc:`color </tutorials/colors/colors>` family [ ``'serif'`` | ``'sans-serif'`` | ``'cursive'`` | ``'fantasy'`` | ``'monospace'`` ] fontproperties a `~matplotlib.font_manager.FontProperties` instance horizontalalignment or ha [ ``'center'`` | ``'right'`` | ``'left'`` ] label any string linespacing `float` multialignment [``'left'`` | ``'right'`` | ``'center'`` ] name or fontname string e.g., [``'Sans'`` | ``'Courier'`` | ``'Helvetica'`` ...] picker [None|float|boolean|callable] position (x, y) rotation [ angle in degrees | ``'vertical'`` | ``'horizontal'`` ] size or fontsize [ size in points | relative size, e.g., ``'smaller'``, ``'x-large'`` ] style or fontstyle [ ``'normal'`` | ``'italic'`` | ``'oblique'`` ] text string or anything printable with '%s' conversion transform a `~matplotlib.transforms.Transform` instance variant [ ``'normal'`` | ``'small-caps'`` ] verticalalignment or va [ ``'center'`` | ``'top'`` | ``'bottom'`` | ``'baseline'`` ] visible bool weight or fontweight [ ``'normal'`` | ``'bold'`` | ``'heavy'`` | ``'light'`` | ``'ultrabold'`` | ``'ultralight'``] x `float` y `float` zorder any number ========================== ====================================================================================================================== You can lay out text with the alignment arguments ``horizontalalignment``, ``verticalalignment``, and ``multialignment``. ``horizontalalignment`` controls whether the x positional argument for the text indicates the left, center or right side of the text bounding box. ``verticalalignment`` controls whether the y positional argument for the text indicates the bottom, center or top side of the text bounding box. ``multialignment``, for newline separated strings only, controls whether the different lines are left, center or right justified. Here is an example which uses the :func:`~matplotlib.pyplot.text` command to show the various alignment possibilities. The use of ``transform=ax.transAxes`` throughout the code indicates that the coordinates are given relative to the axes bounding box, with 0,0 being the lower left of the axes and 1,1 the upper right. """ import matplotlib.pyplot as plt import matplotlib.patches as patches # build a rectangle in axes coords left, width = .25, .5 bottom, height = .25, .5 right = left + width top = bottom + height fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) # axes coordinates are 0,0 is bottom left and 1,1 is upper right p = patches.Rectangle( (left, bottom), width, height, fill=False, transform=ax.transAxes, clip_on=False ) ax.add_patch(p) ax.text(left, bottom, 'left top', horizontalalignment='left', verticalalignment='top', transform=ax.transAxes) ax.text(left, bottom, 'left bottom', horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes) ax.text(right, top, 'right bottom', horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes) ax.text(right, top, 'right top', horizontalalignment='right', verticalalignment='top', transform=ax.transAxes) ax.text(right, bottom, 'center top', horizontalalignment='center', verticalalignment='top', transform=ax.transAxes) ax.text(left, 0.5*(bottom+top), 'right center', horizontalalignment='right', verticalalignment='center', rotation='vertical', transform=ax.transAxes) ax.text(left, 0.5*(bottom+top), 'left center', horizontalalignment='left', verticalalignment='center', rotation='vertical', transform=ax.transAxes) ax.text(0.5*(left+right), 0.5*(bottom+top), 'middle', horizontalalignment='center', verticalalignment='center', fontsize=20, color='red', transform=ax.transAxes) ax.text(right, 0.5*(bottom+top), 'centered', horizontalalignment='center', verticalalignment='center', rotation='vertical', transform=ax.transAxes) ax.text(left, top, 'rotated\nwith newlines', horizontalalignment='center', verticalalignment='center', rotation=45, transform=ax.transAxes) ax.set_axis_off() plt.show() ############################################################################### # ============== # Default Font # ============== # # The base default font is controlled by a set of rcParams. To set the font # for mathematical expressions, use the rcParams beginning with ``mathtext`` # (see :ref:`mathtext <mathtext-fonts>`). # # +---------------------+----------------------------------------------------+ # | rcParam | usage | # +=====================+====================================================+ # | ``'font.family'`` | List of either names of font or ``{'cursive', | # | | 'fantasy', 'monospace', 'sans', 'sans serif', | # | | 'sans-serif', 'serif'}``. | # | | | # +---------------------+----------------------------------------------------+ # | ``'font.style'`` | The default style, ex ``'normal'``, | # | | ``'italic'``. | # | | | # +---------------------+----------------------------------------------------+ # | ``'font.variant'`` | Default variant, ex ``'normal'``, ``'small-caps'`` | # | | (untested) | # +---------------------+----------------------------------------------------+ # | ``'font.stretch'`` | Default stretch, ex ``'normal'``, ``'condensed'`` | # | | (incomplete) | # | | | # +---------------------+----------------------------------------------------+ # | ``'font.weight'`` | Default weight. Either string or integer | # | | | # | | | # +---------------------+----------------------------------------------------+ # | ``'font.size'`` | Default font size in points. Relative font sizes | # | | (``'large'``, ``'x-small'``) are computed against | # | | this size. | # +---------------------+----------------------------------------------------+ # # The mapping between the family aliases (``{'cursive', 'fantasy', # 'monospace', 'sans', 'sans serif', 'sans-serif', 'serif'}``) and actual font names # is controlled by the following rcParams: # # # +------------------------------------------+--------------------------------+ # | family alias | rcParam with mappings | # +==========================================+================================+ # | ``'serif'`` | ``'font.serif'`` | # +------------------------------------------+--------------------------------+ # | ``'monospace'`` | ``'font.monospace'`` | # +------------------------------------------+--------------------------------+ # | ``'fantasy'`` | ``'font.fantasy'`` | # +------------------------------------------+--------------------------------+ # | ``'cursive'`` | ``'font.cursive'`` | # +------------------------------------------+--------------------------------+ # | ``{'sans', 'sans serif', 'sans-serif'}`` | ``'font.sans-serif'`` | # +------------------------------------------+--------------------------------+ # # # which are lists of font names. # # Text with non-latin glyphs # ========================== # # As of v2.0 the :ref:`default font <default_changes_font>` contains # glyphs for many western alphabets, but still does not cover all of the # glyphs that may be required by mpl users. For example, DejaVu has no # coverage of Chinese, Korean, or Japanese. # # # To set the default font to be one that supports the code points you # need, prepend the font name to ``'font.family'`` or the desired alias # lists :: # # matplotlib.rcParams['font.sans-serif'] = ['Source Han Sans TW', 'sans-serif'] # # or set it in your :file:`.matplotlibrc` file:: # # font.sans-serif: Source Han Sans TW, Arial, sans-serif # # To control the font used on per-artist basis use the ``'name'``, # ``'fontname'`` or ``'fontproperties'`` kwargs documented :doc:`above # </tutorials/text/text_props>`. # # # On linux, `fc-list <https://linux.die.net/man/1/fc-list>`__ can be a # useful tool to discover the font name; for example :: # # $ fc-list :lang=zh family # Noto to Sans Mono CJK TC,Noto Sans Mono CJK TC Bold # Noto Sans CJK TC,Noto Sans CJK TC Medium # Noto Sans CJK TC,Noto Sans CJK TC DemiLight # Noto Sans CJK KR,Noto Sans CJK KR Black # Noto Sans CJK TC,Noto Sans CJK TC Black # Noto Sans Mono CJK TC,Noto Sans Mono CJK TC Regular # Noto Sans CJK SC,Noto Sans CJK SC Light # # lists all of the fonts that support Chinese. #
e33f9c5ed591358ae995fd7e046aa0cc55a775cb341ccdce798c9919853e095b
r""" Writing mathematical expressions ================================ An introduction to writing mathematical expressions in Matplotlib. You can use a subset TeX markup in any matplotlib text string by placing it inside a pair of dollar signs ($). Note that you do not need to have TeX installed, since Matplotlib ships its own TeX expression parser, layout engine, and fonts. The layout engine is a fairly direct adaptation of the layout algorithms in Donald Knuth's TeX, so the quality is quite good (matplotlib also provides a ``usetex`` option for those who do want to call out to TeX to generate their text (see :doc:`/tutorials/text/usetex`). Any text element can use math text. You should use raw strings (precede the quotes with an ``'r'``), and surround the math text with dollar signs ($), as in TeX. Regular text and mathtext can be interleaved within the same string. Mathtext can use DejaVu Sans (default), DejaVu Serif, the Computer Modern fonts (from (La)TeX), `STIX <http://www.stixfonts.org/>`_ fonts (with are designed to blend well with Times), or a Unicode font that you provide. The mathtext font can be selected with the customization variable ``mathtext.fontset`` (see :doc:`/tutorials/introductory/customizing`) Here is a simple example:: # plain text plt.title('alpha > beta') produces "alpha > beta". Whereas this:: # math text plt.title(r'$\alpha > \beta$') produces ":mathmpl:`\alpha > \beta`". .. note:: Mathtext should be placed between a pair of dollar signs ($). To make it easy to display monetary values, e.g., "$100.00", if a single dollar sign is present in the entire string, it will be displayed verbatim as a dollar sign. This is a small change from regular TeX, where the dollar sign in non-math text would have to be escaped ('\\\$'). .. note:: While the syntax inside the pair of dollar signs ($) aims to be TeX-like, the text outside does not. In particular, characters such as:: # $ % & ~ _ ^ \ { } \( \) \[ \] have special meaning outside of math mode in TeX. Therefore, these characters will behave differently depending on the rcParam ``text.usetex`` flag. See the :doc:`usetex tutorial </tutorials/text/usetex>` for more information. Subscripts and superscripts --------------------------- To make subscripts and superscripts, use the ``'_'`` and ``'^'`` symbols:: r'$\alpha_i > \beta_i$' .. math:: \alpha_i > \beta_i Some symbols automatically put their sub/superscripts under and over the operator. For example, to write the sum of :mathmpl:`x_i` from :mathmpl:`0` to :mathmpl:`\infty`, you could do:: r'$\sum_{i=0}^\infty x_i$' .. math:: \sum_{i=0}^\infty x_i Fractions, binomials, and stacked numbers ----------------------------------------- Fractions, binomials, and stacked numbers can be created with the ``\frac{}{}``, ``\binom{}{}`` and ``\genfrac{}{}{}{}{}{}`` commands, respectively:: r'$\frac{3}{4} \binom{3}{4} \genfrac{}{}{0}{}{3}{4}$' produces .. math:: \frac{3}{4} \binom{3}{4} \stackrel{}{}{0}{}{3}{4} Fractions can be arbitrarily nested:: r'$\frac{5 - \frac{1}{x}}{4}$' produces .. math:: \frac{5 - \frac{1}{x}}{4} Note that special care needs to be taken to place parentheses and brackets around fractions. Doing things the obvious way produces brackets that are too small:: r'$(\frac{5 - \frac{1}{x}}{4})$' .. math :: (\frac{5 - \frac{1}{x}}{4}) The solution is to precede the bracket with ``\left`` and ``\right`` to inform the parser that those brackets encompass the entire object.:: r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$' .. math :: \left(\frac{5 - \frac{1}{x}}{4}\right) Radicals -------- Radicals can be produced with the ``\sqrt[]{}`` command. For example:: r'$\sqrt{2}$' .. math :: \sqrt{2} Any base can (optionally) be provided inside square brackets. Note that the base must be a simple expression, and can not contain layout commands such as fractions or sub/superscripts:: r'$\sqrt[3]{x}$' .. math :: \sqrt[3]{x} .. _mathtext-fonts: Fonts ----- The default font is *italics* for mathematical symbols. .. note:: This default can be changed using the ``mathtext.default`` rcParam. This is useful, for example, to use the same font as regular non-math text for math text, by setting it to ``regular``. To change fonts, e.g., to write "sin" in a Roman font, enclose the text in a font command:: r'$s(t) = \mathcal{A}\mathrm{sin}(2 \omega t)$' .. math:: s(t) = \mathcal{A}\mathrm{sin}(2 \omega t) More conveniently, many commonly used function names that are typeset in a Roman font have shortcuts. So the expression above could be written as follows:: r'$s(t) = \mathcal{A}\sin(2 \omega t)$' .. math:: s(t) = \mathcal{A}\sin(2 \omega t) Here "s" and "t" are variable in italics font (default), "sin" is in Roman font, and the amplitude "A" is in calligraphy font. Note in the example above the calligraphy ``A`` is squished into the ``sin``. You can use a spacing command to add a little whitespace between them:: r's(t) = \mathcal{A}\/\sin(2 \omega t)' .. Here we cheat a bit: for HTML math rendering, Sphinx relies on MathJax which doesn't actually support the italic correction (\/); instead, use a thin space (\,) which is supported. .. math:: s(t) = \mathcal{A}\,\sin(2 \omega t) The choices available with all fonts are: ========================= ================================ Command Result ========================= ================================ ``\mathrm{Roman}`` :mathmpl:`\mathrm{Roman}` ``\mathit{Italic}`` :mathmpl:`\mathit{Italic}` ``\mathtt{Typewriter}`` :mathmpl:`\mathtt{Typewriter}` ``\mathcal{CALLIGRAPHY}`` :mathmpl:`\mathcal{CALLIGRAPHY}` ========================= ================================ .. role:: math-stix(mathmpl) :fontset: stix When using the `STIX <http://www.stixfonts.org/>`_ fonts, you also have the choice of: ================================ ========================================= Command Result ================================ ========================================= ``\mathbb{blackboard}`` :math-stix:`\mathbb{blackboard}` ``\mathrm{\mathbb{blackboard}}`` :math-stix:`\mathrm{\mathbb{blackboard}}` ``\mathfrak{Fraktur}`` :math-stix:`\mathfrak{Fraktur}` ``\mathsf{sansserif}`` :math-stix:`\mathsf{sansserif}` ``\mathrm{\mathsf{sansserif}}`` :math-stix:`\mathrm{\mathsf{sansserif}}` ================================ ========================================= There are also three global "font sets" to choose from, which are selected using the ``mathtext.fontset`` parameter in :ref:`matplotlibrc <matplotlibrc-sample>`. ``cm``: **Computer Modern (TeX)** .. image:: ../../_static/cm_fontset.png ``stix``: **STIX** (designed to blend well with Times) .. image:: ../../_static/stix_fontset.png ``stixsans``: **STIX sans-serif** .. image:: ../../_static/stixsans_fontset.png Additionally, you can use ``\mathdefault{...}`` or its alias ``\mathregular{...}`` to use the font used for regular text outside of mathtext. There are a number of limitations to this approach, most notably that far fewer symbols will be available, but it can be useful to make math expressions blend well with other text in the plot. Custom fonts ~~~~~~~~~~~~ mathtext also provides a way to use custom fonts for math. This method is fairly tricky to use, and should be considered an experimental feature for patient users only. By setting the rcParam ``mathtext.fontset`` to ``custom``, you can then set the following parameters, which control which font file to use for a particular set of math characters. ============================== ================================= Parameter Corresponds to ============================== ================================= ``mathtext.it`` ``\mathit{}`` or default italic ``mathtext.rm`` ``\mathrm{}`` Roman (upright) ``mathtext.tt`` ``\mathtt{}`` Typewriter (monospace) ``mathtext.bf`` ``\mathbf{}`` bold italic ``mathtext.cal`` ``\mathcal{}`` calligraphic ``mathtext.sf`` ``\mathsf{}`` sans-serif ============================== ================================= Each parameter should be set to a fontconfig font descriptor (as defined in the yet-to-be-written font chapter). .. TODO: Link to font chapter The fonts used should have a Unicode mapping in order to find any non-Latin characters, such as Greek. If you want to use a math symbol that is not contained in your custom fonts, you can set the rcParam ``mathtext.fallback_to_cm`` to ``True`` which will cause the mathtext system to use characters from the default Computer Modern fonts whenever a particular character can not be found in the custom font. Note that the math glyphs specified in Unicode have evolved over time, and many fonts may not have glyphs in the correct place for mathtext. Accents ------- An accent command may precede any symbol to add an accent above it. There are long and short forms for some of them. ============================== ================================= Command Result ============================== ================================= ``\acute a`` or ``\'a`` :mathmpl:`\acute a` ``\bar a`` :mathmpl:`\bar a` ``\breve a`` :mathmpl:`\breve a` ``\ddot a`` or ``\''a`` :mathmpl:`\ddot a` ``\dot a`` or ``\.a`` :mathmpl:`\dot a` ``\grave a`` or ``\`a`` :mathmpl:`\grave a` ``\hat a`` or ``\^a`` :mathmpl:`\hat a` ``\tilde a`` or ``\~a`` :mathmpl:`\tilde a` ``\vec a`` :mathmpl:`\vec a` ``\overline{abc}`` :mathmpl:`\overline{abc}` ============================== ================================= In addition, there are two special accents that automatically adjust to the width of the symbols below: ============================== ================================= Command Result ============================== ================================= ``\widehat{xyz}`` :mathmpl:`\widehat{xyz}` ``\widetilde{xyz}`` :mathmpl:`\widetilde{xyz}` ============================== ================================= Care should be taken when putting accents on lower-case i's and j's. Note that in the following ``\imath`` is used to avoid the extra dot over the i:: r"$\hat i\ \ \hat \imath$" .. math:: \hat i\ \ \hat \imath Symbols ------- You can also use a large number of the TeX symbols, as in ``\infty``, ``\leftarrow``, ``\sum``, ``\int``. .. math_symbol_table:: If a particular symbol does not have a name (as is true of many of the more obscure symbols in the STIX fonts), Unicode characters can also be used:: ur'$\u23ce$' Example ------- Here is an example illustrating many of these features in context. .. figure:: ../../gallery/pyplots/images/sphx_glr_pyplot_mathtext_001.png :target: ../../gallery/pyplots/pyplot_mathtext.html :align: center :scale: 50 Pyplot Mathtext """
3ff0c5b86f88652321ba587db33c17ef15edcf6b04bcb017e9d3159cbaafad25
""" ============= Path Tutorial ============= Defining paths in your Matplotlib visualization. The object underlying all of the :mod:`matplotlib.patch` objects is the :class:`~matplotlib.path.Path`, which supports the standard set of moveto, lineto, curveto commands to draw simple and compound outlines consisting of line segments and splines. The ``Path`` is instantiated with a (N,2) array of (x,y) vertices, and a N-length array of path codes. For example to draw the unit rectangle from (0,0) to (1,1), we could use this code """ import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches verts = [ (0., 0.), # left, bottom (0., 1.), # left, top (1., 1.), # right, top (1., 0.), # right, bottom (0., 0.), # ignored ] codes = [ Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] path = Path(verts, codes) fig, ax = plt.subplots() patch = patches.PathPatch(path, facecolor='orange', lw=2) ax.add_patch(patch) ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) plt.show() ############################################################################### # The following path codes are recognized # # ============== ================================= ==================================================================================================================== # Code Vertices Description # ============== ================================= ==================================================================================================================== # ``STOP`` 1 (ignored) A marker for the end of the entire path (currently not required and ignored) # ``MOVETO`` 1 Pick up the pen and move to the given vertex. # ``LINETO`` 1 Draw a line from the current position to the given vertex. # ``CURVE3`` 2 (1 control point, 1 endpoint) Draw a quadratic Bézier curve from the current position, with the given control point, to the given end point. # ``CURVE4`` 3 (2 control points, 1 endpoint) Draw a cubic Bézier curve from the current position, with the given control points, to the given end point. # ``CLOSEPOLY`` 1 (point itself is ignored) Draw a line segment to the start point of the current polyline. # ============== ================================= ==================================================================================================================== # # # .. path-curves: # # # Bézier example # ============== # # Some of the path components require multiple vertices to specify them: # for example CURVE 3 is a `bézier # <https://en.wikipedia.org/wiki/B%C3%A9zier_curve>`_ curve with one # control point and one end point, and CURVE4 has three vertices for the # two control points and the end point. The example below shows a # CURVE4 Bézier spline -- the bézier curve will be contained in the # convex hull of the start point, the two control points, and the end # point verts = [ (0., 0.), # P0 (0.2, 1.), # P1 (1., 0.8), # P2 (0.8, 0.), # P3 ] codes = [ Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4, ] path = Path(verts, codes) fig, ax = plt.subplots() patch = patches.PathPatch(path, facecolor='none', lw=2) ax.add_patch(patch) xs, ys = zip(*verts) ax.plot(xs, ys, 'x--', lw=2, color='black', ms=10) ax.text(-0.05, -0.05, 'P0') ax.text(0.15, 1.05, 'P1') ax.text(1.05, 0.85, 'P2') ax.text(0.85, -0.05, 'P3') ax.set_xlim(-0.1, 1.1) ax.set_ylim(-0.1, 1.1) plt.show() ############################################################################### # .. compound_paths: # # Compound paths # ============== # # All of the simple patch primitives in matplotlib, Rectangle, Circle, # Polygon, etc, are implemented with simple path. Plotting functions # like :meth:`~matplotlib.axes.Axes.hist` and # :meth:`~matplotlib.axes.Axes.bar`, which create a number of # primitives, e.g., a bunch of Rectangles, can usually be implemented more # efficiently using a compound path. The reason ``bar`` creates a list # of rectangles and not a compound path is largely historical: the # :class:`~matplotlib.path.Path` code is comparatively new and ``bar`` # predates it. While we could change it now, it would break old code, # so here we will cover how to create compound paths, replacing the # functionality in bar, in case you need to do so in your own code for # efficiency reasons, e.g., you are creating an animated bar plot. # # We will make the histogram chart by creating a series of rectangles # for each histogram bar: the rectangle width is the bin width and the # rectangle height is the number of datapoints in that bin. First we'll # create some random normally distributed data and compute the # histogram. Because numpy returns the bin edges and not centers, the # length of ``bins`` is 1 greater than the length of ``n`` in the # example below:: # # # histogram our data with numpy # data = np.random.randn(1000) # n, bins = np.histogram(data, 100) # # We'll now extract the corners of the rectangles. Each of the # ``left``, ``bottom``, etc, arrays below is ``len(n)``, where ``n`` is # the array of counts for each histogram bar:: # # # get the corners of the rectangles for the histogram # left = np.array(bins[:-1]) # right = np.array(bins[1:]) # bottom = np.zeros(len(left)) # top = bottom + n # # Now we have to construct our compound path, which will consist of a # series of ``MOVETO``, ``LINETO`` and ``CLOSEPOLY`` for each rectangle. # For each rectangle, we need 5 vertices: 1 for the ``MOVETO``, 3 for # the ``LINETO``, and 1 for the ``CLOSEPOLY``. As indicated in the # table above, the vertex for the closepoly is ignored but we still need # it to keep the codes aligned with the vertices:: # # nverts = nrects*(1+3+1) # verts = np.zeros((nverts, 2)) # codes = np.ones(nverts, int) * path.Path.LINETO # codes[0::5] = path.Path.MOVETO # codes[4::5] = path.Path.CLOSEPOLY # verts[0::5,0] = left # verts[0::5,1] = bottom # verts[1::5,0] = left # verts[1::5,1] = top # verts[2::5,0] = right # verts[2::5,1] = top # verts[3::5,0] = right # verts[3::5,1] = bottom # # All that remains is to create the path, attach it to a # :class:`~matplotlib.patch.PathPatch`, and add it to our axes:: # # barpath = path.Path(verts, codes) # patch = patches.PathPatch(barpath, facecolor='green', # edgecolor='yellow', alpha=0.5) # ax.add_patch(patch) import numpy as np import matplotlib.patches as patches import matplotlib.path as path fig, ax = plt.subplots() # Fixing random state for reproducibility np.random.seed(19680801) # histogram our data with numpy data = np.random.randn(1000) n, bins = np.histogram(data, 100) # get the corners of the rectangles for the histogram left = np.array(bins[:-1]) right = np.array(bins[1:]) bottom = np.zeros(len(left)) top = bottom + n nrects = len(left) nverts = nrects*(1+3+1) verts = np.zeros((nverts, 2)) codes = np.ones(nverts, int) * path.Path.LINETO codes[0::5] = path.Path.MOVETO codes[4::5] = path.Path.CLOSEPOLY verts[0::5, 0] = left verts[0::5, 1] = bottom verts[1::5, 0] = left verts[1::5, 1] = top verts[2::5, 0] = right verts[2::5, 1] = top verts[3::5, 0] = right verts[3::5, 1] = bottom barpath = path.Path(verts, codes) patch = patches.PathPatch(barpath, facecolor='green', edgecolor='yellow', alpha=0.5) ax.add_patch(patch) ax.set_xlim(left[0], right[-1]) ax.set_ylim(bottom.min(), top.max()) plt.show()
0059330cf04f3eeffb41f3d65cc2ccee5b2663ab94f0804ab4e41dc603b89031
""" ================== Path effects guide ================== Defining paths that objects follow on a canvas. .. py:module:: matplotlib.patheffects Matplotlib's :mod:`~matplotlib.patheffects` module provides functionality to apply a multiple draw stage to any Artist which can be rendered via a :class:`~matplotlib.path.Path`. Artists which can have a path effect applied to them include :class:`~matplotlib.patches.Patch`, :class:`~matplotlib.lines.Line2D`, :class:`~matplotlib.collections.Collection` and even :class:`~matplotlib.text.Text`. Each artist's path effects can be controlled via the ``set_path_effects`` method (:class:`~matplotlib.artist.Artist.set_path_effects`), which takes an iterable of :class:`AbstractPathEffect` instances. The simplest path effect is the :class:`Normal` effect, which simply draws the artist without any effect: """ import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects fig = plt.figure(figsize=(5, 1.5)) text = fig.text(0.5, 0.5, 'Hello path effects world!\nThis is the normal ' 'path effect.\nPretty dull, huh?', ha='center', va='center', size=20) text.set_path_effects([path_effects.Normal()]) plt.show() ############################################################################### # Whilst the plot doesn't look any different to what you would expect without any path # effects, the drawing of the text now been changed to use the path effects # framework, opening up the possibilities for more interesting examples. # # Adding a shadow # --------------- # # A far more interesting path effect than :class:`Normal` is the # drop-shadow, which we can apply to any of our path based artists. The classes # :class:`SimplePatchShadow` and # :class:`SimpleLineShadow` do precisely this by drawing either a filled # patch or a line patch below the original artist: import matplotlib.patheffects as path_effects text = plt.text(0.5, 0.5, 'Hello path effects world!', path_effects=[path_effects.withSimplePatchShadow()]) plt.plot([0, 3, 2, 5], linewidth=5, color='blue', path_effects=[path_effects.SimpleLineShadow(), path_effects.Normal()]) plt.show() ############################################################################### # Notice the two approaches to setting the path effects in this example. The # first uses the ``with*`` classes to include the desired functionality automatically # followed with the "normal" effect, whereas the latter explicitly defines the two path # effects to draw. # # Making an artist stand out # -------------------------- # # One nice way of making artists visually stand out is to draw an outline in a bold # color below the actual artist. The :class:`Stroke` path effect # makes this a relatively simple task: fig = plt.figure(figsize=(7, 1)) text = fig.text(0.5, 0.5, 'This text stands out because of\n' 'its black border.', color='white', ha='center', va='center', size=30) text.set_path_effects([path_effects.Stroke(linewidth=3, foreground='black'), path_effects.Normal()]) plt.show() ############################################################################### # It is important to note that this effect only works because we have drawn the text # path twice; once with a thick black line, and then once with the original text # path on top. # # You may have noticed that the keywords to :class:`Stroke` and # :class:`SimplePatchShadow` and :class:`SimpleLineShadow` are not the usual Artist # keywords (such as ``facecolor`` and ``edgecolor`` etc.). This is because with these # path effects we are operating at lower level of matplotlib. In fact, the keywords # which are accepted are those for a :class:`matplotlib.backend_bases.GraphicsContextBase` # instance, which have been designed for making it easy to create new backends - and not # for its user interface. # # # Greater control of the path effect artist # ----------------------------------------- # # As already mentioned, some of the path effects operate at a lower level than most users # will be used to, meaning that setting keywords such as ``facecolor`` and ``edgecolor`` # raise an AttributeError. Luckily there is a generic :class:`PathPatchEffect` path effect # which creates a :class:`~matplotlib.patches.PathPatch` class with the original path. # The keywords to this effect are identical to those of :class:`~matplotlib.patches.PathPatch`: fig = plt.figure(figsize=(8, 1)) t = fig.text(0.02, 0.5, 'Hatch shadow', fontsize=75, weight=1000, va='center') t.set_path_effects([path_effects.PathPatchEffect(offset=(4, -4), hatch='xxxx', facecolor='gray'), path_effects.PathPatchEffect(edgecolor='white', linewidth=1.1, facecolor='black')]) plt.show() ############################################################################### # .. # Headings for future consideration: # # Implementing a custom path effect # --------------------------------- # # What is going on under the hood # --------------------------------
b2e49fa49a0baddc95d712932461ae30034d79df4d2732efc9d33738719f0ded
""" ======================== Transformations Tutorial ======================== Like any graphics packages, Matplotlib is built on top of a transformation framework to easily move between coordinate systems, the userland `data` coordinate system, the `axes` coordinate system, the `figure` coordinate system, and the `display` coordinate system. In 95% of your plotting, you won't need to think about this, as it happens under the hood, but as you push the limits of custom figure generation, it helps to have an understanding of these objects so you can reuse the existing transformations Matplotlib makes available to you, or create your own (see :mod:`matplotlib.transforms`). The table below summarizes the some useful coordinate systems, the transformation object you should use to work in that coordinate system, and the description of that system. In the `Transformation Object` column, ``ax`` is a :class:`~matplotlib.axes.Axes` instance, and ``fig`` is a :class:`~matplotlib.figure.Figure` instance. +----------------+-----------------------------+-----------------------------------+ |Coordinates |Transformation object |Description | +================+=============================+===================================+ |"data" |``ax.transData`` |The coordinate system for the data,| | | |controlled by xlim and ylim. | +----------------+-----------------------------+-----------------------------------+ |"axes" |``ax.transAxes`` |The coordinate system of the | | | |`~matplotlib.axes.Axes`; (0, 0) | | | |is bottom left of the axes, and | | | |(1, 1) is top right of the axes. | +----------------+-----------------------------+-----------------------------------+ |"figure" |``fig.transFigure`` |The coordinate system of the | | | |`.Figure`; (0, 0) is bottom left | | | |of the figure, and (1, 1) is top | | | |right of the figure. | +----------------+-----------------------------+-----------------------------------+ |"figure-inches" |``fig.dpi_scale_trans`` |The coordinate system of the | | | |`.Figure` in inches; (0, 0) is | | | |bottom left of the figure, and | | | |(width, height) is the top right | | | |of the figure in inches. | +----------------+-----------------------------+-----------------------------------+ |"display" |``None``, or |The pixel coordinate system of the | | |``IdentityTransform()`` |display window; (0, 0) is bottom | | | |left of the window, and (width, | | | |height) is top right of the | | | |display window in pixels. | +----------------+-----------------------------+-----------------------------------+ |"xaxis", |``ax.get_xaxis_transform()``,|Blended coordinate systems; use | |"yaxis" |``ax.get_yaxis_transform()`` |data coordinates on one of the axis| | | |and axes coordinates on the other. | +----------------+-----------------------------+-----------------------------------+ All of the transformation objects in the table above take inputs in their coordinate system, and transform the input to the ``display`` coordinate system. That is why the ``display`` coordinate system has ``None`` for the ``Transformation Object`` column -- it already is in display coordinates. The transformations also know how to invert themselves, to go from ``display`` back to the native coordinate system. This is particularly useful when processing events from the user interface, which typically occur in display space, and you want to know where the mouse click or key-press occurred in your data coordinate system. Note that specifying objects in ``display`` coordinates will change their location if the ``dpi`` of the figure changes. This can cause confusion when printing or changing screen resolution, because the object can change location and size. Therefore it is most common for artists placed in an axes or figure to have their transform set to something *other* than the `~.transforms.IdentityTransform()`; the default when an artist is placed on an axes using `~.Axes.axes.add_artist` is for the transform to be ``ax.transData``. .. _data-coords: Data coordinates ================ Let's start with the most commonly used coordinate, the `data` coordinate system. Whenever you add data to the axes, Matplotlib updates the datalimits, most commonly updated with the :meth:`~matplotlib.axes.Axes.set_xlim` and :meth:`~matplotlib.axes.Axes.set_ylim` methods. For example, in the figure below, the data limits stretch from 0 to 10 on the x-axis, and -1 to 1 on the y-axis. """ import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches x = np.arange(0, 10, 0.005) y = np.exp(-x/2.) * np.sin(2*np.pi*x) fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlim(0, 10) ax.set_ylim(-1, 1) plt.show() ############################################################################### # You can use the ``ax.transData`` instance to transform from your # `data` to your `display` coordinate system, either a single point or a # sequence of points as shown below: # # .. sourcecode:: ipython # # In [14]: type(ax.transData) # Out[14]: <class 'matplotlib.transforms.CompositeGenericTransform'> # # In [15]: ax.transData.transform((5, 0)) # Out[15]: array([ 335.175, 247. ]) # # In [16]: ax.transData.transform([(5, 0), (1, 2)]) # Out[16]: # array([[ 335.175, 247. ], # [ 132.435, 642.2 ]]) # # You can use the :meth:`~matplotlib.transforms.Transform.inverted` # method to create a transform which will take you from display to data # coordinates: # # .. sourcecode:: ipython # # In [41]: inv = ax.transData.inverted() # # In [42]: type(inv) # Out[42]: <class 'matplotlib.transforms.CompositeGenericTransform'> # # In [43]: inv.transform((335.175, 247.)) # Out[43]: array([ 5., 0.]) # # If your are typing along with this tutorial, the exact values of the # display coordinates may differ if you have a different window size or # dpi setting. Likewise, in the figure below, the display labeled # points are probably not the same as in the ipython session because the # documentation figure size defaults are different. x = np.arange(0, 10, 0.005) y = np.exp(-x/2.) * np.sin(2*np.pi*x) fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlim(0, 10) ax.set_ylim(-1, 1) xdata, ydata = 5, 0 xdisplay, ydisplay = ax.transData.transform_point((xdata, ydata)) bbox = dict(boxstyle="round", fc="0.8") arrowprops = dict( arrowstyle="->", connectionstyle="angle,angleA=0,angleB=90,rad=10") offset = 72 ax.annotate('data = (%.1f, %.1f)' % (xdata, ydata), (xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points', bbox=bbox, arrowprops=arrowprops) disp = ax.annotate('display = (%.1f, %.1f)' % (xdisplay, ydisplay), (xdisplay, ydisplay), xytext=(0.5*offset, -offset), xycoords='figure pixels', textcoords='offset points', bbox=bbox, arrowprops=arrowprops) plt.show() ############################################################################### # .. note:: # # If you run the source code in the example above in a GUI backend, # you may also find that the two arrows for the `data` and `display` # annotations do not point to exactly the same point. This is because # the display point was computed before the figure was displayed, and # the GUI backend may slightly resize the figure when it is created. # The effect is more pronounced if you resize the figure yourself. # This is one good reason why you rarely want to work in display # space, but you can connect to the ``'on_draw'`` # :class:`~matplotlib.backend_bases.Event` to update figure # coordinates on figure draws; see :ref:`event-handling-tutorial`. # # When you change the x or y limits of your axes, the data limits are # updated so the transformation yields a new display point. Note that # when we just change the ylim, only the y-display coordinate is # altered, and when we change the xlim too, both are altered. More on # this later when we talk about the # :class:`~matplotlib.transforms.Bbox`. # # .. sourcecode:: ipython # # In [54]: ax.transData.transform((5, 0)) # Out[54]: array([ 335.175, 247. ]) # # In [55]: ax.set_ylim(-1, 2) # Out[55]: (-1, 2) # # In [56]: ax.transData.transform((5, 0)) # Out[56]: array([ 335.175 , 181.13333333]) # # In [57]: ax.set_xlim(10, 20) # Out[57]: (10, 20) # # In [58]: ax.transData.transform((5, 0)) # Out[58]: array([-171.675 , 181.13333333]) # # # .. _axes-coords: # # Axes coordinates # ================ # # After the `data` coordinate system, `axes` is probably the second most # useful coordinate system. Here the point (0, 0) is the bottom left of # your axes or subplot, (0.5, 0.5) is the center, and (1.0, 1.0) is the # top right. You can also refer to points outside the range, so (-0.1, # 1.1) is to the left and above your axes. This coordinate system is # extremely useful when placing text in your axes, because you often # want a text bubble in a fixed, location, e.g., the upper left of the axes # pane, and have that location remain fixed when you pan or zoom. Here # is a simple example that creates four panels and labels them 'A', 'B', # 'C', 'D' as you often see in journals. fig = plt.figure() for i, label in enumerate(('A', 'B', 'C', 'D')): ax = fig.add_subplot(2, 2, i+1) ax.text(0.05, 0.95, label, transform=ax.transAxes, fontsize=16, fontweight='bold', va='top') plt.show() ############################################################################### # You can also make lines or patches in the axes coordinate system, but # this is less useful in my experience than using ``ax.transAxes`` for # placing text. Nonetheless, here is a silly example which plots some # random dots in `data` space, and overlays a semi-transparent # :class:`~matplotlib.patches.Circle` centered in the middle of the axes # with a radius one quarter of the axes -- if your axes does not # preserve aspect ratio (see :meth:`~matplotlib.axes.Axes.set_aspect`), # this will look like an ellipse. Use the pan/zoom tool to move around, # or manually change the data xlim and ylim, and you will see the data # move, but the circle will remain fixed because it is not in `data` # coordinates and will always remain at the center of the axes. fig, ax = plt.subplots() x, y = 10*np.random.rand(2, 1000) ax.plot(x, y, 'go', alpha=0.2) # plot some data in data coordinates circ = mpatches.Circle((0.5, 0.5), 0.25, transform=ax.transAxes, facecolor='blue', alpha=0.75) ax.add_patch(circ) plt.show() ############################################################################### # .. _blended_transformations: # # Blended transformations # ======================= # # Drawing in `blended` coordinate spaces which mix `axes` with `data` # coordinates is extremely useful, for example to create a horizontal # span which highlights some region of the y-data but spans across the # x-axis regardless of the data limits, pan or zoom level, etc. In fact # these blended lines and spans are so useful, we have built in # functions to make them easy to plot (see # :meth:`~matplotlib.axes.Axes.axhline`, # :meth:`~matplotlib.axes.Axes.axvline`, # :meth:`~matplotlib.axes.Axes.axhspan`, # :meth:`~matplotlib.axes.Axes.axvspan`) but for didactic purposes we # will implement the horizontal span here using a blended # transformation. This trick only works for separable transformations, # like you see in normal Cartesian coordinate systems, but not on # inseparable transformations like the # :class:`~matplotlib.projections.polar.PolarAxes.PolarTransform`. import matplotlib.transforms as transforms fig, ax = plt.subplots() x = np.random.randn(1000) ax.hist(x, 30) ax.set_title(r'$\sigma=1 \/ \dots \/ \sigma=2$', fontsize=16) # the x coords of this transformation are data, and the # y coord are axes trans = transforms.blended_transform_factory( ax.transData, ax.transAxes) # highlight the 1..2 stddev region with a span. # We want x to be in data coordinates and y to # span from 0..1 in axes coords rect = mpatches.Rectangle((1, 0), width=1, height=1, transform=trans, color='yellow', alpha=0.5) ax.add_patch(rect) plt.show() ############################################################################### # .. note:: # # The blended transformations where x is in data coords and y in axes # coordinates is so useful that we have helper methods to return the # versions mpl uses internally for drawing ticks, ticklabels, etc. # The methods are :meth:`matplotlib.axes.Axes.get_xaxis_transform` and # :meth:`matplotlib.axes.Axes.get_yaxis_transform`. So in the example # above, the call to # :meth:`~matplotlib.transforms.blended_transform_factory` can be # replaced by ``get_xaxis_transform``:: # # trans = ax.get_xaxis_transform() # # .. _transforms-fig-scale-dpi: # # Plotting in physical units # ========================== # # Sometimes we want an object to be a certain physical size on the plot. # Here we draw the same circle as above, but in physical units. If done # interactively, you can see that changing the size of the figure does # not change the offset of the circle from the lower-left corner, # does not change its size, and the circle remains a circle regardless of # the aspect ratio of the axes. fig, ax = plt.subplots(figsize=(5, 4)) x, y = 10*np.random.rand(2, 1000) ax.plot(x, y*10., 'go', alpha=0.2) # plot some data in data coordinates # add a circle in fixed-units circ = mpatches.Circle((2.5, 2), 1.0, transform=fig.dpi_scale_trans, facecolor='blue', alpha=0.75) ax.add_patch(circ) plt.show() ############################################################################### # If we change the figure size, the circle does not change its absolute # position and is cropped. fig, ax = plt.subplots(figsize=(7, 2)) x, y = 10*np.random.rand(2, 1000) ax.plot(x, y*10., 'go', alpha=0.2) # plot some data in data coordinates # add a circle in fixed-units circ = mpatches.Circle((2.5, 2), 1.0, transform=fig.dpi_scale_trans, facecolor='blue', alpha=0.75) ax.add_patch(circ) plt.show() ############################################################################### # Another use is putting a patch with a set physical dimension around a # data point on the axes. Here we add together two transforms. The # first sets the scaling of how large the ellipse should be and the second # sets its position. The ellipse is then placed at the origin, and then # we use the helper transform :class:`~matplotlib.transforms.ScaledTranslation` # to move it # to the right place in the ``ax.transData`` coordinate system. # This helper is instantiated with:: # # trans = ScaledTranslation(xt, yt, scale_trans) # # where `xt` and `yt` are the translation offsets, and `scale_trans` is # a transformation which scales `xt` and `yt` at transformation time # before applying the offsets. # # Note the use of the plus operator on the transforms below. # This code says: first apply the scale transformation ``fig.dpi_scale_trans`` # to make the ellipse the proper size, but still centered at (0, 0), # and then translate the data to `xdata[0]` and `ydata[0]` in data space. # # In interactive use, the ellipse stays the same size even if the # axes limits are changed via zoom. # fig, ax = plt.subplots() xdata, ydata = (0.2, 0.7), (0.5, 0.5) ax.plot(xdata, ydata, "o") ax.set_xlim((0, 1)) trans = (fig.dpi_scale_trans + transforms.ScaledTranslation(xdata[0], ydata[0], ax.transData)) # plot an ellipse around the point that is 150 x 130 points in diameter... circle = mpatches.Ellipse((0, 0), 150/72, 130/72, angle=40, fill=None, transform=trans) ax.add_patch(circle) plt.show() ############################################################################### # .. note:: # # The order of transformation matters. Here the ellipse # is given the right dimensions in display space *first* and then moved # in data space to the correct spot. # If we had done the ``ScaledTranslation`` first, then # ``xdata[0]`` and ``ydata[0]`` would # first be transformed to ``display`` coordinates (``[ 358.4 475.2]`` on # a 200-dpi monitor) and then those coordinates # would be scaled by ``fig.dpi_scale_trans`` pushing the center of # the ellipse well off the screen (i.e. ``[ 71680. 95040.]``). # # .. _offset-transforms-shadow: # # Using offset transforms to create a shadow effect # ================================================= # # Another use of :class:`~matplotlib.transforms.ScaledTranslation` is to create # a new transformation that is # offset from another transformation, e.g., to place one object shifted a # bit relative to another object. Typically you want the shift to be in # some physical dimension, like points or inches rather than in data # coordinates, so that the shift effect is constant at different zoom # levels and dpi settings. # # One use for an offset is to create a shadow effect, where you draw one # object identical to the first just to the right of it, and just below # it, adjusting the zorder to make sure the shadow is drawn first and # then the object it is shadowing above it. # # Here we apply the transforms in the *opposite* order to the use of # :class:`~matplotlib.transforms.ScaledTranslation` above. The plot is # first made in data units (``ax.transData``) and then shifted by # ``dx`` and ``dy`` points using `fig.dpi_scale_trans`. (In typography, # a`point <https://en.wikipedia.org/wiki/Point_%28typography%29>`_ is # 1/72 inches, and by specifying your offsets in points, your figure # will look the same regardless of the dpi resolution it is saved in.) fig, ax = plt.subplots() # make a simple sine wave x = np.arange(0., 2., 0.01) y = np.sin(2*np.pi*x) line, = ax.plot(x, y, lw=3, color='blue') # shift the object over 2 points, and down 2 points dx, dy = 2/72., -2/72. offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans) shadow_transform = ax.transData + offset # now plot the same data with our offset transform; # use the zorder to make sure we are below the line ax.plot(x, y, lw=3, color='gray', transform=shadow_transform, zorder=0.5*line.get_zorder()) ax.set_title('creating a shadow effect with an offset transform') plt.show() ############################################################################### # .. note:: # # The dpi and inches offset is a # common-enough use case that we have a special helper function to # create it in :func:`matplotlib.transforms.offset_copy`, which returns # a new transform with an added offset. So above we could have done:: # # shadow_transform = transforms.offset_copy(ax.transData, # fig=fig, dx, dy, units='inches') # # # .. _transformation-pipeline: # # The transformation pipeline # =========================== # # The ``ax.transData`` transform we have been working with in this # tutorial is a composite of three different transformations that # comprise the transformation pipeline from `data` -> `display` # coordinates. Michael Droettboom implemented the transformations # framework, taking care to provide a clean API that segregated the # nonlinear projections and scales that happen in polar and logarithmic # plots, from the linear affine transformations that happen when you pan # and zoom. There is an efficiency here, because you can pan and zoom # in your axes which affects the affine transformation, but you may not # need to compute the potentially expensive nonlinear scales or # projections on simple navigation events. It is also possible to # multiply affine transformation matrices together, and then apply them # to coordinates in one step. This is not true of all possible # transformations. # # # Here is how the ``ax.transData`` instance is defined in the basic # separable axis :class:`~matplotlib.axes.Axes` class:: # # self.transData = self.transScale + (self.transLimits + self.transAxes) # # We've been introduced to the ``transAxes`` instance above in # :ref:`axes-coords`, which maps the (0, 0), (1, 1) corners of the # axes or subplot bounding box to `display` space, so let's look at # these other two pieces. # # ``self.transLimits`` is the transformation that takes you from # ``data`` to ``axes`` coordinates; i.e., it maps your view xlim and ylim # to the unit space of the axes (and ``transAxes`` then takes that unit # space to display space). We can see this in action here # # .. sourcecode:: ipython # # In [80]: ax = subplot(111) # # In [81]: ax.set_xlim(0, 10) # Out[81]: (0, 10) # # In [82]: ax.set_ylim(-1, 1) # Out[82]: (-1, 1) # # In [84]: ax.transLimits.transform((0, -1)) # Out[84]: array([ 0., 0.]) # # In [85]: ax.transLimits.transform((10, -1)) # Out[85]: array([ 1., 0.]) # # In [86]: ax.transLimits.transform((10, 1)) # Out[86]: array([ 1., 1.]) # # In [87]: ax.transLimits.transform((5, 0)) # Out[87]: array([ 0.5, 0.5]) # # and we can use this same inverted transformation to go from the unit # `axes` coordinates back to `data` coordinates. # # .. sourcecode:: ipython # # In [90]: inv.transform((0.25, 0.25)) # Out[90]: array([ 2.5, -0.5]) # # The final piece is the ``self.transScale`` attribute, which is # responsible for the optional non-linear scaling of the data, e.g., for # logarithmic axes. When an Axes is initially setup, this is just set to # the identity transform, since the basic Matplotlib axes has linear # scale, but when you call a logarithmic scaling function like # :meth:`~matplotlib.axes.Axes.semilogx` or explicitly set the scale to # logarithmic with :meth:`~matplotlib.axes.Axes.set_xscale`, then the # ``ax.transScale`` attribute is set to handle the nonlinear projection. # The scales transforms are properties of the respective ``xaxis`` and # ``yaxis`` :class:`~matplotlib.axis.Axis` instances. For example, when # you call ``ax.set_xscale('log')``, the xaxis updates its scale to a # :class:`matplotlib.scale.LogScale` instance. # # For non-separable axes the PolarAxes, there is one more piece to # consider, the projection transformation. The ``transData`` # :class:`matplotlib.projections.polar.PolarAxes` is similar to that for # the typical separable matplotlib Axes, with one additional piece # ``transProjection``:: # # self.transData = self.transScale + self.transProjection + \ # (self.transProjectionAffine + self.transAxes) # # ``transProjection`` handles the projection from the space, # e.g., latitude and longitude for map data, or radius and theta for polar # data, to a separable Cartesian coordinate system. There are several # projection examples in the ``matplotlib.projections`` package, and the # best way to learn more is to open the source for those packages and # see how to make your own, since Matplotlib supports extensible axes # and projections. Michael Droettboom has provided a nice tutorial # example of creating a Hammer projection axes; see # :doc:`/gallery/misc/custom_projection`.
d9bbf22dc851fdba46c429782e61521e98352d83f0dbc2a85f23ed445a366522
r""" ============================== Overview of axisartist toolkit ============================== The axisartist toolkit tutorial. .. warning:: *axisartist* uses a custom Axes class (derived from the mpl's original Axes class). As a side effect, some commands (mostly tick-related) do not work. The *axisartist* contains a custom Axes class that is meant to support curvilinear grids (e.g., the world coordinate system in astronomy). Unlike mpl's original Axes class which uses Axes.xaxis and Axes.yaxis to draw ticks, ticklines, etc., axisartist uses a special artist (AxisArtist) that can handle ticks, ticklines, etc. for curved coordinate systems. .. figure:: ../../gallery/axisartist/images/sphx_glr_demo_floating_axis_001.png :target: ../../gallery/axisartist/demo_floating_axis.html :align: center :scale: 50 Demo Floating Axis Since it uses special artists, some Matplotlib commands that work on Axes.xaxis and Axes.yaxis may not work. .. _axisartist_users-guide-index: axisartist ========== The *axisartist* module provides a custom (and very experimental) Axes class, where each axis (left, right, top, and bottom) have a separate associated artist which is responsible for drawing the axis-line, ticks, ticklabels, and labels. You can also create your own axis, which can pass through a fixed position in the axes coordinate, or a fixed position in the data coordinate (i.e., the axis floats around when viewlimit changes). The axes class, by default, has its xaxis and yaxis invisible, and has 4 additional artists which are responsible for drawing the 4 axis spines in "left", "right", "bottom", and "top". They are accessed as ax.axis["left"], ax.axis["right"], and so on, i.e., ax.axis is a dictionary that contains artists (note that ax.axis is still a callable method and it behaves as an original Axes.axis method in Matplotlib). To create an axes, :: import mpl_toolkits.axisartist as AA fig = plt.figure() ax = AA.Axes(fig, [0.1, 0.1, 0.8, 0.8]) fig.add_axes(ax) or to create a subplot :: ax = AA.Subplot(fig, 111) fig.add_subplot(ax) For example, you can hide the right and top spines using:: ax.axis["right"].set_visible(False) ax.axis["top"].set_visible(False) .. figure:: ../../gallery/axisartist/images/sphx_glr_simple_axisline3_001.png :target: ../../gallery/axisartist/simple_axisline3.html :align: center :scale: 50 Simple Axisline3 It is also possible to add a horizontal axis. For example, you may have an horizontal axis at y=0 (in data coordinate). :: ax.axis["y=0"] = ax.new_floating_axis(nth_coord=0, value=0) .. figure:: ../../gallery/axisartist/images/sphx_glr_simple_axisartist1_001.png :target: ../../gallery/axisartist/simple_axisartist1.html :align: center :scale: 50 Simple Axisartist1 Or a fixed axis with some offset :: # make new (right-side) yaxis, but with some offset ax.axis["right2"] = ax.new_fixed_axis(loc="right", offset=(20, 0)) axisartist with ParasiteAxes ---------------------------- Most commands in the axes_grid1 toolkit can take an axes_class keyword argument, and the commands create an axes of the given class. For example, to create a host subplot with axisartist.Axes, :: import mpl_toolkits.axisartist as AA from mpl_toolkits.axes_grid1 import host_subplot host = host_subplot(111, axes_class=AA.Axes) Here is an example that uses ParasiteAxes. .. figure:: ../../gallery/axisartist/images/sphx_glr_demo_parasite_axes2_001.png :target: ../../gallery/axisartist/demo_parasite_axes2.html :align: center :scale: 50 Demo Parasite Axes2 Curvilinear Grid ---------------- The motivation behind the AxisArtist module is to support a curvilinear grid and ticks. .. figure:: ../../gallery/axisartist/images/sphx_glr_demo_curvelinear_grid_001.png :target: ../../gallery/axisartist/demo_curvelinear_grid.html :align: center :scale: 50 Demo Curvelinear Grid Floating Axes ------------- AxisArtist also supports a Floating Axes whose outer axes are defined as floating axis. .. figure:: ../../gallery/axisartist/images/sphx_glr_demo_floating_axes_001.png :target: ../../gallery/axisartist/demo_floating_axes.html :align: center :scale: 50 Demo Floating Axes axisartist namespace ==================== The *axisartist* namespace includes a derived Axes implementation. The biggest difference is that the artists responsible to draw axis line, ticks, ticklabel and axis labels are separated out from the mpl's Axis class, which are much more than artists in the original mpl. This change was strongly motivated to support curvilinear grid. Here are a few things that mpl_toolkits.axisartist.Axes is different from original Axes from mpl. * Axis elements (axis line(spine), ticks, ticklabel and axis labels) are drawn by a AxisArtist instance. Unlike Axis, left, right, top and bottom axis are drawn by separate artists. And each of them may have different tick location and different tick labels. * gridlines are drawn by a Gridlines instance. The change was motivated that in curvilinear coordinate, a gridline may not cross axis-lines (i.e., no associated ticks). In the original Axes class, gridlines are tied to ticks. * ticklines can be rotated if necessary (i.e, along the gridlines) In summary, all these changes was to support * a curvilinear grid. * a floating axis .. figure:: ../../gallery/axisartist/images/sphx_glr_demo_floating_axis_001.png :target: ../../gallery/axisartist/demo_floating_axis.html :align: center :scale: 50 Demo Floating Axis *mpl_toolkits.axisartist.Axes* class defines a *axis* attribute, which is a dictionary of AxisArtist instances. By default, the dictionary has 4 AxisArtist instances, responsible for drawing of left, right, bottom and top axis. xaxis and yaxis attributes are still available, however they are set to not visible. As separate artists are used for rendering axis, some axis-related method in mpl may have no effect. In addition to AxisArtist instances, the mpl_toolkits.axisartist.Axes will have *gridlines* attribute (Gridlines), which obviously draws grid lines. In both AxisArtist and Gridlines, the calculation of tick and grid location is delegated to an instance of GridHelper class. mpl_toolkits.axisartist.Axes class uses GridHelperRectlinear as a grid helper. The GridHelperRectlinear class is a wrapper around the *xaxis* and *yaxis* of mpl's original Axes, and it was meant to work as the way how mpl's original axes works. For example, tick location changes using set_ticks method and etc. should work as expected. But change in artist properties (e.g., color) will not work in general, although some effort has been made so that some often-change attributes (color, etc.) are respected. AxisArtist ========== AxisArtist can be considered as a container artist with following attributes which will draw ticks, labels, etc. * line * major_ticks, major_ticklabels * minor_ticks, minor_ticklabels * offsetText * label line ---- Derived from Line2d class. Responsible for drawing a spinal(?) line. major_ticks, minor_ticks ------------------------ Derived from Line2d class. Note that ticks are markers. major_ticklabels, minor_ticklabels ---------------------------------- Derived from Text. Note that it is not a list of Text artist, but a single artist (similar to a collection). axislabel --------- Derived from Text. Default AxisArtists =================== By default, following for axis artists are defined.:: ax.axis["left"], ax.axis["bottom"], ax.axis["right"], ax.axis["top"] The ticklabels and axislabel of the top and the right axis are set to not visible. For example, if you want to change the color attributes of major_ticklabels of the bottom x-axis :: ax.axis["bottom"].major_ticklabels.set_color("b") Similarly, to make ticklabels invisible :: ax.axis["bottom"].major_ticklabels.set_visible(False) AxisArtist provides a helper method to control the visibility of ticks, ticklabels, and label. To make ticklabel invisible, :: ax.axis["bottom"].toggle(ticklabels=False) To make all of ticks, ticklabels, and (axis) label invisible :: ax.axis["bottom"].toggle(all=False) To turn all off but ticks on :: ax.axis["bottom"].toggle(all=False, ticks=True) To turn all on but (axis) label off :: ax.axis["bottom"].toggle(all=True, label=False)) ax.axis's __getitem__ method can take multiple axis names. For example, to turn ticklabels of "top" and "right" axis on, :: ax.axis["top","right"].toggle(ticklabels=True)) Note that 'ax.axis["top","right"]' returns a simple proxy object that translate above code to something like below. :: for n in ["top","right"]: ax.axis[n].toggle(ticklabels=True)) So, any return values in the for loop are ignored. And you should not use it anything more than a simple method. Like the list indexing ":" means all items, i.e., :: ax.axis[:].major_ticks.set_color("r") changes tick color in all axis. HowTo ===== 1. Changing tick locations and label. Same as the original mpl's axes.:: ax.set_xticks([1,2,3]) 2. Changing axis properties like color, etc. Change the properties of appropriate artists. For example, to change the color of the ticklabels:: ax.axis["left"].major_ticklabels.set_color("r") 3. To change the attributes of multiple axis:: ax.axis["left","bottom"].major_ticklabels.set_color("r") or to change the attributes of all axis:: ax.axis[:].major_ticklabels.set_color("r") 4. To change the tick size (length), you need to use axis.major_ticks.set_ticksize method. To change the direction of the ticks (ticks are in opposite direction of ticklabels by default), use axis.major_ticks.set_tick_out method. To change the pad between ticks and ticklabels, use axis.major_ticklabels.set_pad method. To change the pad between ticklabels and axis label, axis.label.set_pad method. Rotation and Alignment of TickLabels ==================================== This is also quite different from the original mpl and can be confusing. When you want to rotate the ticklabels, first consider using "set_axis_direction" method. :: ax1.axis["left"].major_ticklabels.set_axis_direction("top") ax1.axis["right"].label.set_axis_direction("left") .. figure:: ../../gallery/axisartist/images/sphx_glr_simple_axis_direction01_001.png :target: ../../gallery/axisartist/simple_axis_direction01.html :align: center :scale: 50 Simple Axis Direction01 The parameter for set_axis_direction is one of ["left", "right", "bottom", "top"]. You must understand some underlying concept of directions. 1. There is a reference direction which is defined as the direction of the axis line with increasing coordinate. For example, the reference direction of the left x-axis is from bottom to top. .. figure:: ../../gallery/axisartist/images/sphx_glr_axis_direction_demo_step01_001.png :target: ../../gallery/axisartist/axis_direction_demo_step01.html :align: center :scale: 50 Axis Direction Demo - Step 01 The direction, text angle, and alignments of the ticks, ticklabels and axis-label is determined with respect to the reference direction 2. *ticklabel_direction* is either the right-hand side (+) of the reference direction or the left-hand side (-). .. figure:: ../../gallery/axisartist/images/sphx_glr_axis_direction_demo_step02_001.png :target: ../../gallery/axisartist/axis_direction_demo_step02.html :align: center :scale: 50 Axis Direction Demo - Step 02 3. same for the *label_direction* .. figure:: ../../gallery/axisartist/images/sphx_glr_axis_direction_demo_step03_001.png :target: ../../gallery/axisartist/axis_direction_demo_step03.html :align: center :scale: 50 Axis Direction Demo - Step 03 4. ticks are by default drawn toward the opposite direction of the ticklabels. 5. text rotation of ticklabels and label is determined in reference to the *ticklabel_direction* or *label_direction*, respectively. The rotation of ticklabels and label is anchored. .. figure:: ../../gallery/axisartist/images/sphx_glr_axis_direction_demo_step04_001.png :target: ../../gallery/axisartist/axis_direction_demo_step04.html :align: center :scale: 50 Axis Direction Demo - Step 04 On the other hand, there is a concept of "axis_direction". This is a default setting of above properties for each, "bottom", "left", "top", and "right" axis. ========== =========== ========= ========== ========= ========== ? ? left bottom right top ---------- ----------- --------- ---------- --------- ---------- axislabel direction '-' '+' '+' '-' axislabel rotation 180 0 0 180 axislabel va center top center bottom axislabel ha right center right center ticklabel direction '-' '+' '+' '-' ticklabels rotation 90 0 -90 180 ticklabel ha right center right center ticklabel va center baseline center baseline ========== =========== ========= ========== ========= ========== And, 'set_axis_direction("top")' means to adjust the text rotation etc, for settings suitable for "top" axis. The concept of axis direction can be more clear with curved axis. .. figure:: ../../gallery/axisartist/images/sphx_glr_demo_axis_direction_001.png :target: ../../gallery/axisartist/demo_axis_direction.html :align: center :scale: 50 Demo Axis Direction The axis_direction can be adjusted in the AxisArtist level, or in the level of its child artists, i.e., ticks, ticklabels, and axis-label. :: ax1.axis["left"].set_axis_direction("top") changes axis_direction of all the associated artist with the "left" axis, while :: ax1.axis["left"].major_ticklabels.set_axis_direction("top") changes the axis_direction of only the major_ticklabels. Note that set_axis_direction in the AxisArtist level changes the ticklabel_direction and label_direction, while changing the axis_direction of ticks, ticklabels, and axis-label does not affect them. If you want to make ticks outward and ticklabels inside the axes, use invert_ticklabel_direction method. :: ax.axis[:].invert_ticklabel_direction() A related method is "set_tick_out". It makes ticks outward (as a matter of fact, it makes ticks toward the opposite direction of the default direction). :: ax.axis[:].major_ticks.set_tick_out(True) .. figure:: ../../gallery/axisartist/images/sphx_glr_simple_axis_direction03_001.png :target: ../../gallery/axisartist/simple_axis_direction03.html :align: center :scale: 50 Simple Axis Direction03 So, in summary, * AxisArtist's methods * set_axis_direction : "left", "right", "bottom", or "top" * set_ticklabel_direction : "+" or "-" * set_axislabel_direction : "+" or "-" * invert_ticklabel_direction * Ticks' methods (major_ticks and minor_ticks) * set_tick_out : True or False * set_ticksize : size in points * TickLabels' methods (major_ticklabels and minor_ticklabels) * set_axis_direction : "left", "right", "bottom", or "top" * set_rotation : angle with respect to the reference direction * set_ha and set_va : see below * AxisLabels' methods (label) * set_axis_direction : "left", "right", "bottom", or "top" * set_rotation : angle with respect to the reference direction * set_ha and set_va Adjusting ticklabels alignment ------------------------------ Alignment of TickLabels are treated specially. See below .. figure:: ../../gallery/axisartist/images/sphx_glr_demo_ticklabel_alignment_001.png :target: ../../gallery/axisartist/demo_ticklabel_alignment.html :align: center :scale: 50 Demo Ticklabel Alignment Adjusting pad ------------- To change the pad between ticks and ticklabels :: ax.axis["left"].major_ticklabels.set_pad(10) Or ticklabels and axis-label :: ax.axis["left"].label.set_pad(10) .. figure:: ../../gallery/axisartist/images/sphx_glr_simple_axis_pad_001.png :target: ../../gallery/axisartist/simple_axis_pad.html :align: center :scale: 50 Simple Axis Pad GridHelper ========== To actually define a curvilinear coordinate, you have to use your own grid helper. A generalised version of grid helper class is supplied and this class should suffice in most of cases. A user may provide two functions which defines a transformation (and its inverse pair) from the curved coordinate to (rectilinear) image coordinate. Note that while ticks and grids are drawn for curved coordinate, the data transform of the axes itself (ax.transData) is still rectilinear (image) coordinate. :: from mpl_toolkits.axisartist.grid_helper_curvelinear \ import GridHelperCurveLinear from mpl_toolkits.axisartist import Subplot # from curved coordinate to rectlinear coordinate. def tr(x, y): x, y = np.asarray(x), np.asarray(y) return x, y-x # from rectlinear coordinate to curved coordinate. def inv_tr(x,y): x, y = np.asarray(x), np.asarray(y) return x, y+x grid_helper = GridHelperCurveLinear((tr, inv_tr)) ax1 = Subplot(fig, 1, 1, 1, grid_helper=grid_helper) fig.add_subplot(ax1) You may use matplotlib's Transform instance instead (but a inverse transformation must be defined). Often, coordinate range in a curved coordinate system may have a limited range, or may have cycles. In those cases, a more customized version of grid helper is required. :: import mpl_toolkits.axisartist.angle_helper as angle_helper # PolarAxes.PolarTransform takes radian. However, we want our coordinate # system in degree tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform() # extreme finder : find a range of coordinate. # 20, 20 : number of sampling points along x, y direction # The first coordinate (longitude, but theta in polar) # has a cycle of 360 degree. # The second coordinate (latitude, but radius in polar) has a minimum of 0 extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, lon_cycle = 360, lat_cycle = None, lon_minmax = None, lat_minmax = (0, np.inf), ) # Find a grid values appropriate for the coordinate (degree, # minute, second). The argument is a approximate number of grids. grid_locator1 = angle_helper.LocatorDMS(12) # And also uses an appropriate formatter. Note that,the # acceptable Locator and Formatter class is a bit different than # that of mpl's, and you cannot directly use mpl's Locator and # Formatter here (but may be possible in the future). tick_formatter1 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, tick_formatter1=tick_formatter1 ) Again, the *transData* of the axes is still a rectilinear coordinate (image coordinate). You may manually do conversion between two coordinates, or you may use Parasite Axes for convenience.:: ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper) # A parasite axes with given transform ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal") # note that ax2.transData == tr + ax1.transData # Anything you draw in ax2 will match the ticks and grids of ax1. ax1.parasites.append(ax2) .. figure:: ../../gallery/axisartist/images/sphx_glr_demo_curvelinear_grid_001.png :target: ../../gallery/axisartist/demo_curvelinear_grid.html :align: center :scale: 50 Demo Curvelinear Grid FloatingAxis ============ A floating axis is an axis one of whose data coordinate is fixed, i.e, its location is not fixed in Axes coordinate but changes as axes data limits changes. A floating axis can be created using *new_floating_axis* method. However, it is your responsibility that the resulting AxisArtist is properly added to the axes. A recommended way is to add it as an item of Axes's axis attribute.:: # floating axis whose first (index starts from 0) coordinate # (theta) is fixed at 60 ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60) axis.label.set_text(r"$\theta = 60^{\circ}$") axis.label.set_visible(True) See the first example of this page. Current Limitations and TODO's ============================== The code need more refinement. Here is a incomplete list of issues and TODO's * No easy way to support a user customized tick location (for curvilinear grid). A new Locator class needs to be created. * FloatingAxis may have coordinate limits, e.g., a floating axis of x = 0, but y only spans from 0 to 1. * The location of axislabel of FloatingAxis needs to be optionally given as a coordinate value. ex, a floating axis of x=0 with label at y=1 """
aba3b2a4d7159a78b89c46a3efd78b43a4340f6346cc8ad2d04c50056648f80c
r""" ============================== Overview of axes_grid1 toolkit ============================== Controlling the layout of plots with the axes_grid toolkit. .. _axes_grid1_users-guide-index: What is axes_grid1 toolkit? =========================== *axes_grid1* is a collection of helper classes to ease displaying (multiple) images with matplotlib. In matplotlib, the axes location (and size) is specified in the normalized figure coordinates, which may not be ideal for displaying images that needs to have a given aspect ratio. For example, it helps if you have a colorbar whose height always matches that of the image. `ImageGrid`_, `RGB Axes`_ and `AxesDivider`_ are helper classes that deals with adjusting the location of (multiple) Axes. They provides a framework to adjust the position of multiple axes at the drawing time. `ParasiteAxes`_ provides twinx(or twiny)-like features so that you can plot different data (e.g., different y-scale) in a same Axes. `AnchoredArtists`_ includes custom artists which are placed at some anchored position, like the legend. .. figure:: ../../gallery/axes_grid1/images/sphx_glr_demo_axes_grid_001.png :target: ../../gallery/axes_grid1/demo_axes_grid.html :align: center :scale: 50 Demo Axes Grid axes_grid1 ========== ImageGrid --------- A class that creates a grid of Axes. In matplotlib, the axes location (and size) is specified in the normalized figure coordinates. This may not be ideal for images that needs to be displayed with a given aspect ratio. For example, displaying images of a same size with some fixed padding between them cannot be easily done in matplotlib. ImageGrid is used in such case. .. figure:: ../../gallery/axes_grid1/images/sphx_glr_simple_axesgrid_001.png :target: ../../gallery/axes_grid1/simple_axesgrid.html :align: center :scale: 50 Simple Axesgrid * The position of each axes is determined at the drawing time (see `AxesDivider`_), so that the size of the entire grid fits in the given rectangle (like the aspect of axes). Note that in this example, the paddings between axes are fixed even if you changes the figure size. * axes in the same column has a same axes width (in figure coordinate), and similarly, axes in the same row has a same height. The widths (height) of the axes in the same row (column) are scaled according to their view limits (xlim or ylim). .. figure:: ../../gallery/axes_grid1/images/sphx_glr_simple_axesgrid2_001.png :target: ../../gallery/axes_grid1/simple_axesgrid2.html :align: center :scale: 50 Simple Axes Grid * xaxis are shared among axes in a same column. Similarly, yaxis are shared among axes in a same row. Therefore, changing axis properties (view limits, tick location, etc. either by plot commands or using your mouse in interactive backends) of one axes will affect all other shared axes. When initialized, ImageGrid creates given number (*ngrids* or *ncols* * *nrows* if *ngrids* is None) of Axes instances. A sequence-like interface is provided to access the individual Axes instances (e.g., grid[0] is the first Axes in the grid. See below for the order of axes). ImageGrid takes following arguments, ============= ======== ================================================ Name Default Description ============= ======== ================================================ fig rect nrows_ncols number of rows and cols. e.g., (2,2) ngrids None number of grids. nrows x ncols if None direction "row" increasing direction of axes number. [row|column] axes_pad 0.02 pad between axes in inches add_all True Add axes to figures if True share_all False xaxis & yaxis of all axes are shared if True aspect True aspect of axes label_mode "L" location of tick labels thaw will be displayed. "1" (only the lower left axes), "L" (left most and bottom most axes), or "all". cbar_mode None [None|single|each] cbar_location "right" [right|top] cbar_pad None pad between image axes and colorbar axes cbar_size "5%" size of the colorbar axes_class None ============= ======== ================================================ *rect* specifies the location of the grid. You can either specify coordinates of the rectangle to be used (e.g., (0.1, 0.1, 0.8, 0.8) as in the Axes), or the subplot-like position (e.g., "121"). *direction* means the increasing direction of the axes number. *aspect* By default (False), widths and heights of axes in the grid are scaled independently. If True, they are scaled according to their data limits (similar to aspect parameter in mpl). *share_all* if True, xaxis and yaxis of all axes are shared. *direction* direction of increasing axes number. For "row", +---------+---------+ | grid[0] | grid[1] | +---------+---------+ | grid[2] | grid[3] | +---------+---------+ For "column", +---------+---------+ | grid[0] | grid[2] | +---------+---------+ | grid[1] | grid[3] | +---------+---------+ You can also create a colorbar (or colorbars). You can have colorbar for each axes (cbar_mode="each"), or you can have a single colorbar for the grid (cbar_mode="single"). The colorbar can be placed on your right, or top. The axes for each colorbar is stored as a *cbar_axes* attribute. The examples below show what you can do with ImageGrid. .. figure:: ../../gallery/axes_grid1/images/sphx_glr_demo_axes_grid_001.png :target: ../../gallery/axes_grid1/demo_axes_grid.html :align: center :scale: 50 Demo Axes Grid AxesDivider Class ----------------- Behind the scene, the ImageGrid class and the RGBAxes class utilize the AxesDivider class, whose role is to calculate the location of the axes at drawing time. While a more about the AxesDivider is (will be) explained in (yet to be written) AxesDividerGuide, direct use of the AxesDivider class will not be necessary for most users. The axes_divider module provides a helper function make_axes_locatable, which can be useful. It takes a existing axes instance and create a divider for it. :: ax = subplot(1,1,1) divider = make_axes_locatable(ax) *make_axes_locatable* returns an instance of the AxesLocator class, derived from the Locator. It provides *append_axes* method that creates a new axes on the given side of ("top", "right", "bottom" and "left") of the original axes. colorbar whose height (or width) in sync with the master axes ------------------------------------------------------------- .. figure:: ../../gallery/axes_grid1/images/sphx_glr_simple_colorbar_001.png :target: ../../gallery/axes_grid1/simple_colorbar.html :align: center :scale: 50 Simple Colorbar scatter_hist.py with AxesDivider ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The "scatter_hist.py" example in mpl can be rewritten using *make_axes_locatable*. :: axScatter = subplot(111) axScatter.scatter(x, y) axScatter.set_aspect(1.) # create new axes on the right and on the top of the current axes. divider = make_axes_locatable(axScatter) axHistx = divider.append_axes("top", size=1.2, pad=0.1, sharex=axScatter) axHisty = divider.append_axes("right", size=1.2, pad=0.1, sharey=axScatter) # the scatter plot: # histograms bins = np.arange(-lim, lim + binwidth, binwidth) axHistx.hist(x, bins=bins) axHisty.hist(y, bins=bins, orientation='horizontal') See the full source code below. .. figure:: ../../gallery/axes_grid1/images/sphx_glr_scatter_hist_locatable_axes_001.png :target: ../../gallery/axes_grid1/scatter_hist_locatable_axes.html :align: center :scale: 50 Scatter Hist The scatter_hist using the AxesDivider has some advantage over the original scatter_hist.py in mpl. For example, you can set the aspect ratio of the scatter plot, even with the x-axis or y-axis is shared accordingly. ParasiteAxes ------------ The ParasiteAxes is an axes whose location is identical to its host axes. The location is adjusted in the drawing time, thus it works even if the host change its location (e.g., images). In most cases, you first create a host axes, which provides a few method that can be used to create parasite axes. They are *twinx*, *twiny* (which are similar to twinx and twiny in the matplotlib) and *twin*. *twin* takes an arbitrary transformation that maps between the data coordinates of the host axes and the parasite axes. *draw* method of the parasite axes are never called. Instead, host axes collects artists in parasite axes and draw them as if they belong to the host axes, i.e., artists in parasite axes are merged to those of the host axes and then drawn according to their zorder. The host and parasite axes modifies some of the axes behavior. For example, color cycle for plot lines are shared between host and parasites. Also, the legend command in host, creates a legend that includes lines in the parasite axes. To create a host axes, you may use *host_subplot* or *host_axes* command. Example 1. twinx ~~~~~~~~~~~~~~~~ .. figure:: ../../gallery/axes_grid1/images/sphx_glr_parasite_simple_001.png :target: ../../gallery/axes_grid1/parasite_simple.html :align: center :scale: 50 Parasite Simple Example 2. twin ~~~~~~~~~~~~~~~ *twin* without a transform argument assumes that the parasite axes has the same data transform as the host. This can be useful when you want the top(or right)-axis to have different tick-locations, tick-labels, or tick-formatter for bottom(or left)-axis. :: ax2 = ax.twin() # now, ax2 is responsible for "top" axis and "right" axis ax2.set_xticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi]) ax2.set_xticklabels(["0", r"$\frac{1}{2}\pi$", r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"]) .. figure:: ../../gallery/axes_grid1/images/sphx_glr_simple_axisline4_001.png :target: ../../gallery/axes_grid1/simple_axisline4.html :align: center :scale: 50 Simple Axisline4 A more sophisticated example using twin. Note that if you change the x-limit in the host axes, the x-limit of the parasite axes will change accordingly. .. figure:: ../../gallery/axes_grid1/images/sphx_glr_parasite_simple2_001.png :target: ../../gallery/axes_grid1/parasite_simple2.html :align: center :scale: 50 Parasite Simple2 AnchoredArtists --------------- It's a collection of artists whose location is anchored to the (axes) bbox, like the legend. It is derived from *OffsetBox* in mpl, and artist need to be drawn in the canvas coordinate. But, there is a limited support for an arbitrary transform. For example, the ellipse in the example below will have width and height in the data coordinate. .. figure:: ../../gallery/axes_grid1/images/sphx_glr_simple_anchored_artists_001.png :target: ../../gallery/axes_grid1/simple_anchored_artists.html :align: center :scale: 50 Simple Anchored Artists InsetLocator ------------ :mod:`mpl_toolkits.axes_grid1.inset_locator` provides helper classes and functions to place your (inset) axes at the anchored position of the parent axes, similarly to AnchoredArtist. Using :func:`mpl_toolkits.axes_grid1.inset_locator.inset_axes`, you can have inset axes whose size is either fixed, or a fixed proportion of the parent axes. For example,:: inset_axes = inset_axes(parent_axes, width="30%", # width = 30% of parent_bbox height=1., # height : 1 inch loc='lower left') creates an inset axes whose width is 30% of the parent axes and whose height is fixed at 1 inch. You may creates your inset whose size is determined so that the data scale of the inset axes to be that of the parent axes multiplied by some factor. For example, :: inset_axes = zoomed_inset_axes(ax, 0.5, # zoom = 0.5 loc='upper right') creates an inset axes whose data scale is half of the parent axes. Here is complete examples. .. figure:: ../../gallery/axes_grid1/images/sphx_glr_inset_locator_demo_001.png :target: ../../gallery/axes_grid1/inset_locator_demo.html :align: center :scale: 50 Inset Locator Demo For example, :func:`zoomed_inset_axes` can be used when you want the inset represents the zoom-up of the small portion in the parent axes. And :mod:`~mpl_toolkits/axes_grid/inset_locator` provides a helper function :func:`mark_inset` to mark the location of the area represented by the inset axes. .. figure:: ../../gallery/axes_grid1/images/sphx_glr_inset_locator_demo2_001.png :target: ../../gallery/axes_grid1/inset_locator_demo2.html :align: center :scale: 50 Inset Locator Demo2 RGB Axes ~~~~~~~~ RGBAxes is a helper class to conveniently show RGB composite images. Like ImageGrid, the location of axes are adjusted so that the area occupied by them fits in a given rectangle. Also, the xaxis and yaxis of each axes are shared. :: from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes fig = plt.figure() ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8]) r, g, b = get_rgb() # r,g,b are 2-d images ax.imshow_rgb(r, g, b, origin="lower", interpolation="nearest") .. figure:: ../../gallery/axes_grid1/images/sphx_glr_simple_rgb_001.png :target: ../../gallery/axes_grid1/simple_rgb.html :align: center :scale: 50 Simple Rgb AxesDivider =========== The axes_divider module provides helper classes to adjust the axes positions of a set of images at drawing time. * :mod:`~mpl_toolkits.axes_grid1.axes_size` provides a class of units that are used to determine the size of each axes. For example, you can specify a fixed size. * :class:`~mpl_toolkits.axes_grid1.axes_size.Divider` is the class that calculates the axes position. It divides the given rectangular area into several areas. The divider is initialized by setting the lists of horizontal and vertical sizes on which the division will be based. Then use :meth:`~mpl_toolkits.axes_grid1.axes_size.Divider.new_locator`, which returns a callable object that can be used to set the axes_locator of the axes. First, initialize the divider by specifying its grids, i.e., horizontal and vertical. for example,:: rect = [0.2, 0.2, 0.6, 0.6] horiz=[h0, h1, h2, h3] vert=[v0, v1, v2] divider = Divider(fig, rect, horiz, vert) where, rect is a bounds of the box that will be divided and h0,..h3, v0,..v2 need to be an instance of classes in the :mod:`~mpl_toolkits.axes_grid1.axes_size`. They have *get_size* method that returns a tuple of two floats. The first float is the relative size, and the second float is the absolute size. Consider a following grid. +-----+-----+-----+-----+ | v0 | | | | +-----+-----+-----+-----+ | v1 | | | | +-----+-----+-----+-----+ |h0,v2| h1 | h2 | h3 | +-----+-----+-----+-----+ * v0 => 0, 2 * v1 => 2, 0 * v2 => 3, 0 The height of the bottom row is always 2 (axes_divider internally assumes that the unit is inches). The first and the second rows have a height ratio of 2:3. For example, if the total height of the grid is 6, then the first and second row will each occupy 2/(2+3) and 3/(2+3) of (6-1) inches. The widths of the horizontal columns will be similarly determined. When the aspect ratio is set, the total height (or width) will be adjusted accordingly. The :mod:`mpl_toolkits.axes_grid1.axes_size` contains several classes that can be used to set the horizontal and vertical configurations. For example, for vertical configuration one could use:: from mpl_toolkits.axes_grid1.axes_size import Fixed, Scaled vert = [Fixed(2), Scaled(2), Scaled(3)] After you set up the divider object, then you create a locator instance that will be given to the axes object.:: locator = divider.new_locator(nx=0, ny=1) ax.set_axes_locator(locator) The return value of the new_locator method is an instance of the AxesLocator class. It is a callable object that returns the location and size of the cell at the first column and the second row. You may create a locator that spans over multiple cells.:: locator = divider.new_locator(nx=0, nx=2, ny=1) The above locator, when called, will return the position and size of the cells spanning the first and second column and the first row. In this example, it will return [0:2, 1]. See the example, .. figure:: ../../gallery/axes_grid1/images/sphx_glr_simple_axes_divider2_001.png :target: ../../gallery/axes_grid1/simple_axes_divider2.html :align: center :scale: 50 Simple Axes Divider2 You can adjust the size of each axes according to its x or y data limits (AxesX and AxesY). .. figure:: ../../gallery/axes_grid1/images/sphx_glr_simple_axes_divider3_001.png :target: ../../gallery/axes_grid1/simple_axes_divider3.html :align: center :scale: 50 Simple Axes Divider3 """