hash
stringlengths
64
64
content
stringlengths
0
1.51M
027cb06589f657f84e8fa6dbf439ccac00f3e55a4cbee522a1cf3b003aceab5e
""" ========================== Axis Direction Demo Step01 ========================== """ import matplotlib.pyplot as plt import mpl_toolkits.axisartist as axisartist def setup_axes(fig, rect): ax = axisartist.Subplot(fig, rect) fig.add_axes(ax) ax.set_ylim(-0.1, 1.5) ax.set_yticks([0, 1]) ax.axis[:].set_visible(False) ax.axis["x"] = ax.new_floating_axis(1, 0.5) ax.axis["x"].set_axisline_style("->", size=1.5) return ax fig = plt.figure(figsize=(3, 2.5)) fig.subplots_adjust(top=0.8) ax1 = setup_axes(fig, "111") ax1.axis["x"].set_axis_direction("left") plt.show()
95003ce2ae9cb5d7154820b6b461b05ff77b5f1d3d33df63df7e6964aa115683
""" ======================== Demo Ticklabel Direction ======================== """ import matplotlib.pyplot as plt import mpl_toolkits.axisartist.axislines as axislines def setup_axes(fig, rect): ax = axislines.Subplot(fig, rect) fig.add_subplot(ax) ax.set_yticks([0.2, 0.8]) ax.set_xticks([0.2, 0.8]) return ax fig = plt.figure(figsize=(6, 3)) fig.subplots_adjust(bottom=0.2) ax = setup_axes(fig, 131) for axis in ax.axis.values(): axis.major_ticks.set_tick_out(True) # or you can simply do "ax.axis[:].major_ticks.set_tick_out(True)" ax = setup_axes(fig, 132) ax.axis["left"].set_axis_direction("right") ax.axis["bottom"].set_axis_direction("top") ax.axis["right"].set_axis_direction("left") ax.axis["top"].set_axis_direction("bottom") ax = setup_axes(fig, 133) ax.axis["left"].set_axis_direction("right") ax.axis[:].major_ticks.set_tick_out(True) ax.axis["left"].label.set_text("Long Label Left") ax.axis["bottom"].label.set_text("Label Bottom") ax.axis["right"].label.set_text("Long Label Right") ax.axis["right"].label.set_visible(True) ax.axis["left"].label.set_pad(0) ax.axis["bottom"].label.set_pad(10) plt.show()
c702109403ce1bf8278fbb4f0f4d4431b59890f7b4bec1e419a2349d8396789c
""" ================== Demo Floating Axis ================== Axis within rectangular frame The following code demonstrates how to put a floating polar curve within a rectangular box. In order to get a better sense of polar curves, please look at demo_curvelinear_grid.py. """ import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.axisartist.angle_helper as angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D from mpl_toolkits.axisartist import SubplotHost from mpl_toolkits.axisartist import GridHelperCurveLinear def curvelinear_test2(fig): """Polar projection, but in a rectangular box. """ # see demo_curvelinear_grid.py for details tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform() extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf), ) grid_locator1 = angle_helper.LocatorDMS(12) tick_formatter1 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, tick_formatter1=tick_formatter1 ) ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) fig.add_subplot(ax1) # Now creates floating axis # floating axis whose first 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) # floating axis whose second coordinate (r) is fixed at 6 ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6) axis.label.set_text(r"$r = 6$") ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) ax1.grid(True) fig = plt.figure(figsize=(5, 5)) curvelinear_test2(fig) plt.show()
40bc729a9d6fdd543c24187de0eb3af6242dfb3e5c63badd69787c5183f3ecd9
""" =================== Demo Axis Direction =================== """ import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.axisartist.angle_helper as angle_helper import mpl_toolkits.axisartist.grid_finder as grid_finder from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D import mpl_toolkits.axisartist as axisartist from mpl_toolkits.axisartist.grid_helper_curvelinear import \ GridHelperCurveLinear def setup_axes(fig, rect): """ polar projection, but in a rectangular box. """ # see demo_curvelinear_grid.py for details tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform() extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, lon_cycle=360, lat_cycle=None, lon_minmax=None, lat_minmax=(0, np.inf), ) grid_locator1 = angle_helper.LocatorDMS(12) grid_locator2 = grid_finder.MaxNLocator(5) tick_formatter1 = angle_helper.FormatterDMS() grid_helper = GridHelperCurveLinear(tr, extreme_finder=extreme_finder, grid_locator1=grid_locator1, grid_locator2=grid_locator2, tick_formatter1=tick_formatter1 ) ax1 = axisartist.Subplot(fig, rect, grid_helper=grid_helper) ax1.axis[:].toggle(ticklabels=False) fig.add_subplot(ax1) ax1.set_aspect(1.) ax1.set_xlim(-5, 12) ax1.set_ylim(-5, 10) return ax1 def add_floating_axis1(ax1): ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 30) axis.label.set_text(r"$\theta = 30^{\circ}$") axis.label.set_visible(True) return axis def add_floating_axis2(ax1): ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6) axis.label.set_text(r"$r = 6$") axis.label.set_visible(True) return axis fig = plt.figure(figsize=(8, 4)) fig.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99, wspace=0.01, hspace=0.01) for i, d in enumerate(["bottom", "left", "top", "right"]): ax1 = setup_axes(fig, rect=241++i) axis = add_floating_axis1(ax1) axis.set_axis_direction(d) ax1.annotate(d, (0, 1), (5, -5), xycoords="axes fraction", textcoords="offset points", va="top", ha="left") for i, d in enumerate(["bottom", "left", "top", "right"]): ax1 = setup_axes(fig, rect=245++i) axis = add_floating_axis2(ax1) axis.set_axis_direction(d) ax1.annotate(d, (0, 1), (5, -5), xycoords="axes fraction", textcoords="offset points", va="top", ha="left") plt.show()
5790405556a11796f772aec25571572b3f621f1cc9d7174e605a5d8af3b92d6b
""" =============== Basic pie chart =============== Demo of a basic pie chart plus a few additional features. In addition to the basic pie chart, this demo shows a few optional features: * slice labels * auto-labeling the percentage * offsetting a slice with "explode" * drop-shadow * custom start angle Note about the custom start angle: The default ``startangle`` is 0, which would start the "Frogs" slice on the positive x-axis. This example sets ``startangle = 90`` such that everything is rotated counter-clockwise by 90 degrees, and the frog slice starts on the positive y-axis. """ import matplotlib.pyplot as plt # Pie chart, where the slices will be ordered and plotted counter-clockwise: labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') fig1, ax1 = plt.subplots() ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.pie matplotlib.pyplot.pie
68b78ac82349d6807b41a2b45ae18148b62fa8f15491d64997299625d028fc9f
""" ========= Pie Demo2 ========= Make a pie charts using :meth:`~.axes.Axes.pie`. This example demonstrates some pie chart features like labels, varying size, autolabeling the percentage, offsetting a slice and adding a shadow. """ import matplotlib.pyplot as plt # Some data labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' fracs = [15, 30, 45, 10] # Make figure and axes fig, axs = plt.subplots(2, 2) # A standard pie plot axs[0, 0].pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True) # Shift the second slice using explode axs[0, 1].pie(fracs, labels=labels, autopct='%.0f%%', shadow=True, explode=(0, 0.1, 0, 0)) # Adapt radius and text size for a smaller pie patches, texts, autotexts = axs[1, 0].pie(fracs, labels=labels, autopct='%.0f%%', textprops={'size': 'smaller'}, shadow=True, radius=0.5) # Make percent texts even smaller plt.setp(autotexts, size='x-small') autotexts[0].set_color('white') # Use a smaller explode and turn of the shadow for better visibility patches, texts, autotexts = axs[1, 1].pie(fracs, labels=labels, autopct='%.0f%%', textprops={'size': 'smaller'}, shadow=False, radius=0.5, explode=(0, 0.05, 0, 0)) plt.setp(autotexts, size='x-small') autotexts[0].set_color('white') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.pie matplotlib.pyplot.pie
ce0a85e85185bf4c96376ff7a8e18e03c4e41018e3ec4e0e99e93fa8bbe3386e
""" ================= Nested pie charts ================= The following examples show two ways to build a nested pie chart in Matplotlib. Such charts are often referred to as donut charts. """ import matplotlib.pyplot as plt import numpy as np ############################################################################### # The most straightforward way to build a pie chart is to use the # :meth:`pie method <matplotlib.axes.Axes.pie>` # # In this case, pie takes values corresponding to counts in a group. # We'll first generate some fake data, corresponding to three groups. # In the inner circle, we'll treat each number as belonging to its # own group. In the outer circle, we'll plot them as members of their # original 3 groups. # # The effect of the donut shape is achieved by setting a `width` to # the pie's wedges through the `wedgeprops` argument. fig, ax = plt.subplots() size = 0.3 vals = np.array([[60., 32.], [37., 40.], [29., 10.]]) cmap = plt.get_cmap("tab20c") outer_colors = cmap(np.arange(3)*4) inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10])) ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors, wedgeprops=dict(width=size, edgecolor='w')) ax.pie(vals.flatten(), radius=1-size, colors=inner_colors, wedgeprops=dict(width=size, edgecolor='w')) ax.set(aspect="equal", title='Pie plot with `ax.pie`') plt.show() ############################################################################### # However, you can accomplish the same output by using a bar plot on # axes with a polar coordinate system. This may give more flexibility on # the exact design of the plot. # # In this case, we need to map x-values of the bar chart onto radians of # a circle. The cumulative sum of the values are used as the edges # of the bars. fig, ax = plt.subplots(subplot_kw=dict(polar=True)) size = 0.3 vals = np.array([[60., 32.], [37., 40.], [29., 10.]]) #normalize vals to 2 pi valsnorm = vals/np.sum(vals)*2*np.pi #obtain the ordinates of the bar edges valsleft = np.cumsum(np.append(0, valsnorm.flatten()[:-1])).reshape(vals.shape) cmap = plt.get_cmap("tab20c") outer_colors = cmap(np.arange(3)*4) inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10])) ax.bar(x=valsleft[:, 0], width=valsnorm.sum(axis=1), bottom=1-size, height=size, color=outer_colors, edgecolor='w', linewidth=1, align="edge") ax.bar(x=valsleft.flatten(), width=valsnorm.flatten(), bottom=1-2*size, height=size, color=inner_colors, edgecolor='w', linewidth=1, align="edge") ax.set(title="Pie plot with `ax.bar` and polar coordinates") ax.set_axis_off() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.pie matplotlib.pyplot.pie matplotlib.axes.Axes.bar matplotlib.pyplot.bar matplotlib.projections.polar matplotlib.axes.Axes.set matplotlib.axes.Axes.set_axis_off
331e98d7dab71415812745fc9fbe665d7f47dc00123c30dfa24f19dca3684a56
""" ========== Polar Demo ========== Demo of a line plot on a polar axis. """ import numpy as np import matplotlib.pyplot as plt r = np.arange(0, 2, 0.01) theta = 2 * np.pi * r ax = plt.subplot(111, projection='polar') ax.plot(theta, r) ax.set_rmax(2) ax.set_rticks([0.5, 1, 1.5, 2]) # Less radial ticks ax.set_rlabel_position(-22.5) # Move radial labels away from plotted line ax.grid(True) ax.set_title("A line plot on a polar axis", va='bottom') 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.projections.polar matplotlib.projections.polar.PolarAxes matplotlib.projections.polar.PolarAxes.set_rticks matplotlib.projections.polar.PolarAxes.set_rmax matplotlib.projections.polar.PolarAxes.set_rlabel_position
7ff2419bfb15a309c3c5a69924f250819a17913d21418a61b321c66ff0206607
""" ========== Bar of pie ========== Make a "bar of pie" chart where the first slice of the pie is "exploded" into a bar chart with a further breakdown of said slice's characteristics. The example demonstrates using a figure with multiple sets of axes and using the axes patches list to add two ConnectionPatches to link the subplot charts. """ import matplotlib.pyplot as plt from matplotlib.patches import ConnectionPatch import numpy as np # make figure and assign axis objects fig = plt.figure(figsize=(9, 5.0625)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) fig.subplots_adjust(wspace=0) # pie chart parameters ratios = [.27, .56, .17] labels = ['Approve', 'Disapprove', 'Undecided'] explode = [0.1, 0, 0] # rotate so that first wedge is split by the x-axis angle = -180 * ratios[0] ax1.pie(ratios, autopct='%1.1f%%', startangle=angle, labels=labels, explode=explode) # bar chart parameters xpos = 0 bottom = 0 ratios = [.33, .54, .07, .06] width = .2 colors = [[.1, .3, .5], [.1, .3, .3], [.1, .3, .7], [.1, .3, .9]] for j in range(len(ratios)): height = ratios[j] ax2.bar(xpos, height, width, bottom=bottom, color=colors[j]) ypos = bottom + ax2.patches[j].get_height() / 2 bottom += height ax2.text(xpos, ypos, "%d%%" % (ax2.patches[j].get_height() * 100), ha='center') ax2.set_title('Age of approvers') ax2.legend(('50-65', 'Over 65', '35-49', 'Under 35')) ax2.axis('off') ax2.set_xlim(- 2.5 * width, 2.5 * width) # use ConnectionPatch to draw lines between the two plots # get the wedge data theta1, theta2 = ax1.patches[0].theta1, ax1.patches[0].theta2 center, r = ax1.patches[0].center, ax1.patches[0].r bar_height = sum([item.get_height() for item in ax2.patches]) # draw top connecting line x = r * np.cos(np.pi / 180 * theta2) + center[0] y = np.sin(np.pi / 180 * theta2) + center[1] con = ConnectionPatch(xyA=(- width / 2, bar_height), xyB=(x, y), coordsA="data", coordsB="data", axesA=ax2, axesB=ax1) con.set_color([0, 0, 0]) con.set_linewidth(4) ax2.add_artist(con) # draw bottom connecting line x = r * np.cos(np.pi / 180 * theta1) + center[0] y = np.sin(np.pi / 180 * theta1) + center[1] con = ConnectionPatch(xyA=(- width / 2, 0), xyB=(x, y), coordsA="data", coordsB="data", axesA=ax2, axesB=ax1) con.set_color([0, 0, 0]) ax2.add_artist(con) con.set_linewidth(4) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.pie matplotlib.axes.Axes.bar matplotlib.pyplot matplotlib.patches.ConnectionPatch
ca00684ec46c7b0016440e574c2a23448d9b167c70b4224e0c925a4b973e1d5f
""" ========================== Scatter plot on polar axis ========================== Size increases radially in this example and color increases with angle (just to verify the symbols are being scattered correctly). """ import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) # Compute areas and colors N = 150 r = 2 * np.random.rand(N) theta = 2 * np.pi * np.random.rand(N) area = 200 * r**2 colors = theta fig = plt.figure() ax = fig.add_subplot(111, projection='polar') c = ax.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75) ############################################################################### # Scatter plot on polar axis, with offset origin # ---------------------------------------------- # # The main difference with the previous plot is the configuration of the origin # radius, producing an annulus. Additionally, the theta zero location is set to # rotate the plot. fig = plt.figure() ax = fig.add_subplot(111, polar=True) c = ax.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75) ax.set_rorigin(-2.5) ax.set_theta_zero_location('W', offset=10) ############################################################################### # Scatter plot on polar axis confined to a sector # ----------------------------------------------- # # The main difference with the previous plots is the configuration of the # theta start and end limits, producing a sector instead of a full circle. fig = plt.figure() ax = fig.add_subplot(111, polar=True) c = ax.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75) ax.set_thetamin(45) ax.set_thetamax(135) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.scatter matplotlib.pyplot.scatter matplotlib.projections.polar matplotlib.projections.polar.PolarAxes.set_rorigin matplotlib.projections.polar.PolarAxes.set_theta_zero_location matplotlib.projections.polar.PolarAxes.set_thetamin matplotlib.projections.polar.PolarAxes.set_thetamax
c14586124ae336789d09b34836977e834d9955001f9bca9a664386152e80d965
""" ========================== Labeling a pie and a donut ========================== Welcome to the matplotlib bakery. We will create a pie and a donut chart through the :meth:`pie method <matplotlib.axes.Axes.pie>` and show how to label them with a :meth:`legend <matplotlib.axes.Axes.legend>` as well as with :meth:`annotations <matplotlib.axes.Axes.annotate>`. """ ############################################################################### # As usual we would start by defining the imports and create a figure with # subplots. # Now it's time for the pie. Starting with a pie recipe, we create the data # and a list of labels from it. # # We can provide a function to the ``autopct`` argument, which will expand # automatic percentage labeling by showing absolute values; we calculate # the latter back from relative data and the known sum of all values. # # We then create the pie and store the returned objects for later. # The first returned element of the returned tuple is a list of the wedges. # Those are # :class:`matplotlib.patches.Wedge <matplotlib.patches.Wedge>` patches, which # can directly be used as the handles for a legend. We can use the # legend's ``bbox_to_anchor`` argument to position the legend outside of # the pie. Here we use the axes coordinates ``(1, 0, 0.5, 1)`` together # with the location ``"center left"``; i.e. # the left central point of the legend will be at the left central point of the # bounding box, spanning from ``(1,0)`` to ``(1.5,1)`` in axes coordinates. import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal")) recipe = ["375 g flour", "75 g sugar", "250 g butter", "300 g berries"] data = [float(x.split()[0]) for x in recipe] ingredients = [x.split()[-1] for x in recipe] def func(pct, allvals): absolute = int(pct/100.*np.sum(allvals)) return "{:.1f}%\n({:d} g)".format(pct, absolute) wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data), textprops=dict(color="w")) ax.legend(wedges, ingredients, title="Ingredients", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1)) plt.setp(autotexts, size=8, weight="bold") ax.set_title("Matplotlib bakery: A pie") plt.show() ############################################################################### # Now it's time for the donut. Starting with a donut recipe, we transcribe # the data to numbers (converting 1 egg to 50 g), and directly plot the pie. # The pie? Wait... it's going to be donut, is it not? # Well, as we see here, the donut is a pie, having a certain ``width`` set to # the wedges, which is different from its radius. It's as easy as it gets. # This is done via the ``wedgeprops`` argument. # # We then want to label the wedges via # :meth:`annotations <matplotlib.axes.Axes.annotate>`. We first create some # dictionaries of common properties, which we can later pass as keyword # argument. We then iterate over all wedges and for each # # * calculate the angle of the wedge's center, # * from that obtain the coordinates of the point at that angle on the # circumference, # * determine the horizontal alignment of the text, depending on which side # of the circle the point lies, # * update the connection style with the obtained angle to have the annotation # arrow point outwards from the donut, # * finally, create the annotation with all the previously # determined parameters. fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal")) recipe = ["225 g flour", "90 g sugar", "1 egg", "60 g butter", "100 ml milk", "1/2 package of yeast"] data = [225, 90, 50, 60, 100, 5] wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=-40) bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72) kw = dict(arrowprops=dict(arrowstyle="-"), bbox=bbox_props, zorder=0, va="center") for i, p in enumerate(wedges): ang = (p.theta2 - p.theta1)/2. + p.theta1 y = np.sin(np.deg2rad(ang)) x = np.cos(np.deg2rad(ang)) horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))] connectionstyle = "angle,angleA=0,angleB={}".format(ang) kw["arrowprops"].update({"connectionstyle": connectionstyle}) ax.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y), horizontalalignment=horizontalalignment, **kw) ax.set_title("Matplotlib bakery: A donut") plt.show() ############################################################################### # And here it is, the donut. Note however, that if we were to use this recipe, # the ingredients would suffice for around 6 donuts - producing one huge # donut is untested and might result in kitchen errors. ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.pie matplotlib.pyplot.pie matplotlib.axes.Axes.legend matplotlib.pyplot.legend
c3562809553aa5302a43cd4b25631af347c4cae80c323121f67d7fa6dad35557
""" ============ Polar Legend ============ Demo of a legend on a polar-axis plot. """ import matplotlib.pyplot as plt import numpy as np # radar green, solid grid lines plt.rc('grid', color='#316931', linewidth=1, linestyle='-') plt.rc('xtick', labelsize=15) plt.rc('ytick', labelsize=15) # force square figure and square axes looks better for polar, IMO fig = plt.figure(figsize=(8, 8)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection='polar', facecolor='#d5de9c') r = np.arange(0, 3.0, 0.01) theta = 2 * np.pi * r ax.plot(theta, r, color='#ee8d18', lw=3, label='a line') ax.plot(0.5 * theta, r, color='blue', ls='--', lw=3, label='another line') ax.legend() 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.legend matplotlib.projections.polar matplotlib.projections.polar.PolarAxes
8c2fc053237045a57be685620aa84057672b034abf1f50937a97f8a58f05fb87
""" ======================= Bar chart on polar axis ======================= Demo of bar plot on a polar axis. """ import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) # Compute pie slices N = 20 theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False) radii = 10 * np.random.rand(N) width = np.pi / 4 * np.random.rand(N) colors = plt.cm.viridis(radii / 10.) ax = plt.subplot(111, projection='polar') ax.bar(theta, radii, width=width, bottom=0.0, color=colors, alpha=0.5) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.bar matplotlib.pyplot.bar matplotlib.projections.polar
44cf80a8bfaaadcd76a07ca4ecc3c0c4e18f8ca5a475b62fb3b6aca2041d0857
""" ================ Image Nonuniform ================ This illustrates the NonUniformImage class. It is not available via an Axes method but it is easily added to an Axes instance as shown here. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.image import NonUniformImage from matplotlib import cm interp = 'nearest' # Linear x array for cell centers: x = np.linspace(-4, 4, 9) # Highly nonlinear x array: x2 = x**3 y = np.linspace(-4, 4, 9) z = np.sqrt(x[np.newaxis, :]**2 + y[:, np.newaxis]**2) fig, axs = plt.subplots(nrows=2, ncols=2, constrained_layout=True) fig.suptitle('NonUniformImage class', fontsize='large') ax = axs[0, 0] im = NonUniformImage(ax, interpolation=interp, extent=(-4, 4, -4, 4), cmap=cm.Purples) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim(-4, 4) ax.set_ylim(-4, 4) ax.set_title(interp) ax = axs[0, 1] im = NonUniformImage(ax, interpolation=interp, extent=(-64, 64, -4, 4), cmap=cm.Purples) im.set_data(x2, y, z) ax.images.append(im) ax.set_xlim(-64, 64) ax.set_ylim(-4, 4) ax.set_title(interp) interp = 'bilinear' ax = axs[1, 0] im = NonUniformImage(ax, interpolation=interp, extent=(-4, 4, -4, 4), cmap=cm.Purples) im.set_data(x, y, z) ax.images.append(im) ax.set_xlim(-4, 4) ax.set_ylim(-4, 4) ax.set_title(interp) ax = axs[1, 1] im = NonUniformImage(ax, interpolation=interp, extent=(-64, 64, -4, 4), cmap=cm.Purples) im.set_data(x2, y, z) ax.images.append(im) ax.set_xlim(-64, 64) ax.set_ylim(-4, 4) ax.set_title(interp) plt.show()
9ad297f5a2199853a24342b365fb49b5f338a30c879187725da2e742f7c23f87
""" ============= QuadMesh Demo ============= `~.axes.Axes.pcolormesh` uses a `~matplotlib.collections.QuadMesh`, a faster generalization of `~.axes.Axes.pcolor`, but with some restrictions. This demo illustrates a bug in quadmesh with masked data. """ import copy from matplotlib import cm, pyplot as plt import numpy as np n = 12 x = np.linspace(-1.5, 1.5, n) y = np.linspace(-1.5, 1.5, n * 2) X, Y = np.meshgrid(x, y) Qx = np.cos(Y) - np.cos(X) Qz = np.sin(Y) + np.sin(X) Z = np.sqrt(X**2 + Y**2) / 5 Z = (Z - Z.min()) / (Z.max() - Z.min()) # The color array can include masked values. Zm = np.ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z) fig, axs = plt.subplots(nrows=1, ncols=3) axs[0].pcolormesh(Qx, Qz, Z, shading='gouraud') axs[0].set_title('Without masked values') # You can control the color of the masked region. We copy the default colormap # before modifying it. cmap = copy.copy(cm.get_cmap(plt.rcParams['image.cmap'])) cmap.set_bad('y', 1.0) axs[1].pcolormesh(Qx, Qz, Zm, shading='gouraud', cmap=cmap) axs[1].set_title('With masked values') # Or use the default, which is transparent. axs[2].pcolormesh(Qx, Qz, Zm, shading='gouraud') axs[2].set_title('With masked values') fig.tight_layout() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown in this example: import matplotlib matplotlib.axes.Axes.pcolormesh matplotlib.pyplot.pcolormesh
91925124dec610fe855bb30e154ae2ae934481ba6c89b35cfb065d2ec5cdbede
""" ================= Contourf Hatching ================= Demo filled contour plots with hatched patterns. """ import matplotlib.pyplot as plt import numpy as np # invent some numbers, turning the x and y arrays into simple # 2d arrays, which make combining them together easier. x = np.linspace(-3, 5, 150).reshape(1, -1) y = np.linspace(-3, 5, 120).reshape(-1, 1) z = np.cos(x) + np.sin(y) # we no longer need x and y to be 2 dimensional, so flatten them. x, y = x.flatten(), y.flatten() ############################################################################### # Plot 1: the simplest hatched plot with a colorbar fig1, ax1 = plt.subplots() cs = ax1.contourf(x, y, z, hatches=['-', '/', '\\', '//'], cmap='gray', extend='both', alpha=0.5) fig1.colorbar(cs) ############################################################################### # Plot 2: a plot of hatches without color with a legend fig2, ax2 = plt.subplots() n_levels = 6 ax2.contour(x, y, z, n_levels, colors='black', linestyles='-') cs = ax2.contourf(x, y, z, n_levels, colors='none', hatches=['.', '/', '\\', None, '\\\\', '*'], extend='lower') # create a legend for the contour set artists, labels = cs.legend_elements() ax2.legend(artists, labels, handleheight=2) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.contour matplotlib.pyplot.contour matplotlib.axes.Axes.contourf matplotlib.pyplot.contourf matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.axes.Axes.legend matplotlib.pyplot.legend matplotlib.contour.ContourSet matplotlib.contour.ContourSet.legend_elements
0f8919c63267155eb24425429e293bac959b12ffd1ab01373f4779979a986f94
""" =============== Shading example =============== Example showing how to make shaded relief plots like Mathematica_ or `Generic Mapping Tools`_. .. _Mathematica: http://reference.wolfram.com/mathematica/ref/ReliefPlot.html .. _Generic Mapping Tools: https://gmt.soest.hawaii.edu/ """ import numpy as np from matplotlib import cbook import matplotlib.pyplot as plt from matplotlib.colors import LightSource def main(): # Test data x, y = np.mgrid[-5:5:0.05, -5:5:0.05] z = 5 * (np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2)) with cbook.get_sample_data('jacksboro_fault_dem.npz') as file, \ np.load(file) as dem: elev = dem['elevation'] fig = compare(z, plt.cm.copper) fig.suptitle('HSV Blending Looks Best with Smooth Surfaces', y=0.95) fig = compare(elev, plt.cm.gist_earth, ve=0.05) fig.suptitle('Overlay Blending Looks Best with Rough Surfaces', y=0.95) plt.show() def compare(z, cmap, ve=1): # Create subplots and hide ticks fig, axs = plt.subplots(ncols=2, nrows=2) for ax in axs.flat: ax.set(xticks=[], yticks=[]) # Illuminate the scene from the northwest ls = LightSource(azdeg=315, altdeg=45) axs[0, 0].imshow(z, cmap=cmap) axs[0, 0].set(xlabel='Colormapped Data') axs[0, 1].imshow(ls.hillshade(z, vert_exag=ve), cmap='gray') axs[0, 1].set(xlabel='Illumination Intensity') rgb = ls.shade(z, cmap=cmap, vert_exag=ve, blend_mode='hsv') axs[1, 0].imshow(rgb) axs[1, 0].set(xlabel='Blend Mode: "hsv" (default)') rgb = ls.shade(z, cmap=cmap, vert_exag=ve, blend_mode='overlay') axs[1, 1].imshow(rgb) axs[1, 1].set(xlabel='Blend Mode: "overlay"') return fig if __name__ == '__main__': main() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown in this example: import matplotlib matplotlib.colors.LightSource matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow
b8a73bf684ee32344a096d419ef2dabe26fb63439e73d3d3261f71837e972166
""" ============ Contour Demo ============ Illustrate simple contour plotting, contours on an image with a colorbar for the contours, and labelled contours. See also the :doc:`contour image example </gallery/images_contours_and_fields/contour_image>`. """ import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt 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 ############################################################################### # Create a simple contour plot with labels using default colors. The # inline argument to clabel will control whether the labels are draw # over the line segments of the contour, removing the lines beneath # the label fig, ax = plt.subplots() CS = ax.contour(X, Y, Z) ax.clabel(CS, inline=1, fontsize=10) ax.set_title('Simplest default with labels') ############################################################################### # contour labels can be placed manually by providing list of positions # (in data coordinate). See ginput_manual_clabel.py for interactive # placement. fig, ax = plt.subplots() CS = ax.contour(X, Y, Z) manual_locations = [(-1, -1.4), (-0.62, -0.7), (-2, 0.5), (1.7, 1.2), (2.0, 1.4), (2.4, 1.7)] ax.clabel(CS, inline=1, fontsize=10, manual=manual_locations) ax.set_title('labels at selected locations') ############################################################################### # You can force all the contours to be the same color. fig, ax = plt.subplots() CS = ax.contour(X, Y, Z, 6, colors='k', # negative contours will be dashed by default ) ax.clabel(CS, fontsize=9, inline=1) ax.set_title('Single color - negative contours dashed') ############################################################################### # You can set negative contours to be solid instead of dashed: matplotlib.rcParams['contour.negative_linestyle'] = 'solid' fig, ax = plt.subplots() CS = ax.contour(X, Y, Z, 6, colors='k', # negative contours will be dashed by default ) ax.clabel(CS, fontsize=9, inline=1) ax.set_title('Single color - negative contours solid') ############################################################################### # And you can manually specify the colors of the contour fig, ax = plt.subplots() CS = ax.contour(X, Y, Z, 6, linewidths=np.arange(.5, 4, .5), colors=('r', 'green', 'blue', (1, 1, 0), '#afeeee', '0.5') ) ax.clabel(CS, fontsize=9, inline=1) ax.set_title('Crazy lines') ############################################################################### # Or you can use a colormap to specify the colors; the default # colormap will be used for the contour lines fig, ax = plt.subplots() 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', cmap='flag', linewidths=2, extent=(-3, 3, -2, 2)) # Thicken the zero contour. zc = CS.collections[6] plt.setp(zc, linewidth=4) ax.clabel(CS, levels[1::2], # label every second level inline=1, fmt='%1.1f', fontsize=14) # make a colorbar for the contour lines CB = fig.colorbar(CS, shrink=0.8, extend='both') ax.set_title('Lines with colorbar') # We can still add a colorbar for the image, too. CBI = fig.colorbar(im, orientation='horizontal', shrink=0.8) # This makes the original colorbar look a bit out of place, # so let's improve its position. l, b, w, h = ax.get_position().bounds ll, bb, ww, hh = CB.ax.get_position().bounds CB.ax.set_position([ll, b + 0.1*h, ww, h*0.8]) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown # in this example: import matplotlib matplotlib.axes.Axes.contour matplotlib.pyplot.contour matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.axes.Axes.clabel matplotlib.pyplot.clabel matplotlib.axes.Axes.set_position matplotlib.axes.Axes.get_position
56f887aa3ddb1230b274b336bc91df2a63a7d1fc1e13ac534df34216fc628d43
""" =============== Tricontour Demo =============== Contour plots of unstructured triangular grids. """ import matplotlib.pyplot as plt import matplotlib.tri as tri import numpy as np ############################################################################### # Creating a Triangulation without specifying the triangles results in the # Delaunay triangulation of the points. # First create the x and y coordinates of the points. n_angles = 48 n_radii = 8 min_radius = 0.25 radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi / n_angles x = (radii * np.cos(angles)).flatten() y = (radii * np.sin(angles)).flatten() z = (np.cos(radii) * np.cos(3 * angles)).flatten() # Create the Triangulation; no triangles so Delaunay triangulation created. triang = tri.Triangulation(x, y) # Mask off unwanted triangles. triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < min_radius) ############################################################################### # pcolor plot. fig1, ax1 = plt.subplots() ax1.set_aspect('equal') tcf = ax1.tricontourf(triang, z) fig1.colorbar(tcf) ax1.tricontour(triang, z, colors='k') ax1.set_title('Contour plot of Delaunay triangulation') ############################################################################### # You can specify your own triangulation rather than perform a Delaunay # triangulation of the points, where each triangle is given by the indices of # the three points that make up the triangle, ordered in either a clockwise or # anticlockwise manner. xy = np.asarray([ [-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890], [-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898], [-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919], [-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942], [-0.062, 0.949], [-0.054, 0.958], [-0.069, 0.954], [-0.087, 0.952], [-0.087, 0.959], [-0.080, 0.966], [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965], [-0.097, 0.975], [-0.092, 0.984], [-0.101, 0.980], [-0.108, 0.980], [-0.104, 0.987], [-0.102, 0.993], [-0.115, 1.001], [-0.099, 0.996], [-0.101, 1.007], [-0.090, 1.010], [-0.087, 1.021], [-0.069, 1.021], [-0.052, 1.022], [-0.052, 1.017], [-0.069, 1.010], [-0.064, 1.005], [-0.048, 1.005], [-0.031, 1.005], [-0.031, 0.996], [-0.040, 0.987], [-0.045, 0.980], [-0.052, 0.975], [-0.040, 0.973], [-0.026, 0.968], [-0.020, 0.954], [-0.006, 0.947], [ 0.003, 0.935], [ 0.006, 0.926], [ 0.005, 0.921], [ 0.022, 0.923], [ 0.033, 0.912], [ 0.029, 0.905], [ 0.017, 0.900], [ 0.012, 0.895], [ 0.027, 0.893], [ 0.019, 0.886], [ 0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879], [-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872], [-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933], [-0.077, 0.990], [-0.059, 0.993]]) x = np.degrees(xy[:, 0]) y = np.degrees(xy[:, 1]) x0 = -5 y0 = 52 z = np.exp(-0.01 * ((x - x0) ** 2 + (y - y0) ** 2)) triangles = np.asarray([ [67, 66, 1], [65, 2, 66], [ 1, 66, 2], [64, 2, 65], [63, 3, 64], [60, 59, 57], [ 2, 64, 3], [ 3, 63, 4], [ 0, 67, 1], [62, 4, 63], [57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [ 4, 62, 68], [ 6, 5, 9], [61, 68, 62], [69, 68, 61], [ 9, 5, 70], [ 6, 8, 7], [ 4, 70, 5], [ 8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9], [54, 53, 55], [56, 55, 53], [68, 70, 4], [52, 56, 53], [11, 10, 12], [69, 71, 68], [68, 13, 70], [10, 70, 13], [51, 50, 52], [13, 68, 71], [52, 71, 69], [12, 10, 13], [71, 52, 50], [71, 14, 13], [50, 49, 71], [49, 48, 71], [14, 16, 15], [14, 71, 48], [17, 19, 18], [17, 20, 19], [48, 16, 14], [48, 47, 16], [47, 46, 16], [16, 46, 45], [23, 22, 24], [21, 24, 22], [17, 16, 45], [20, 17, 45], [21, 25, 24], [27, 26, 28], [20, 72, 21], [25, 21, 72], [45, 72, 20], [25, 28, 26], [44, 73, 45], [72, 45, 73], [28, 25, 29], [29, 25, 31], [43, 73, 44], [73, 43, 40], [72, 73, 39], [72, 31, 25], [42, 40, 43], [31, 30, 29], [39, 73, 40], [42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38], [33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]]) ############################################################################### # Rather than create a Triangulation object, can simply pass x, y and triangles # arrays to tripcolor directly. It would be better to use a Triangulation # object if the same triangulation was to be used more than once to save # duplicated calculations. fig2, ax2 = plt.subplots() ax2.set_aspect('equal') tcf = ax2.tricontourf(x, y, triangles, z) fig2.colorbar(tcf) ax2.set_title('Contour plot of user-specified triangulation') ax2.set_xlabel('Longitude (degrees)') ax2.set_ylabel('Latitude (degrees)') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.tricontourf matplotlib.pyplot.tricontourf matplotlib.tri.Triangulation
1e396a388bdd68bcf9a8856ff2f3a2a93204d31adfd5532cec6eb3e6e1c86379
""" ============ Layer Images ============ Layer images above one another using alpha blending """ import matplotlib.pyplot as plt import numpy as np def func3(x, y): return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2 + y**2)) # make these smaller to increase the resolution dx, dy = 0.05, 0.05 x = np.arange(-3.0, 3.0, dx) y = np.arange(-3.0, 3.0, dy) X, Y = np.meshgrid(x, y) # when layering multiple images, the images need to have the same # extent. This does not mean they need to have the same shape, but # they both need to render to the same coordinate system determined by # xmin, xmax, ymin, ymax. Note if you use different interpolations # for the images their apparent extent could be different due to # interpolation edge effects extent = np.min(x), np.max(x), np.min(y), np.max(y) fig = plt.figure(frameon=False) Z1 = np.add.outer(range(8), range(8)) % 2 # chessboard im1 = plt.imshow(Z1, cmap=plt.cm.gray, interpolation='nearest', extent=extent) Z2 = func3(X, Y) im2 = plt.imshow(Z2, cmap=plt.cm.viridis, alpha=.9, interpolation='bilinear', extent=extent) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown # in this example: import matplotlib matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow
e971a28f852e7d1bcd7f32b76701f82f8656106b534b20c35e5c05c79103df89
""" ========== Image Demo ========== Many ways to plot images in Matplotlib. The most common way to plot images in Matplotlib is with :meth:`~.axes.Axes.imshow`. The following examples demonstrate much of the functionality of imshow and the many images you can create. """ import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt import matplotlib.cbook as cbook from matplotlib.path import Path from matplotlib.patches import PathPatch ############################################################################### # First we'll generate a simple bivariate normal distribution. delta = 0.025 x = y = np.arange(-3.0, 3.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 fig, ax = plt.subplots() im = ax.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn, origin='lower', extent=[-3, 3, -3, 3], vmax=abs(Z).max(), vmin=-abs(Z).max()) plt.show() ############################################################################### # It is also possible to show images of pictures. # A sample image with cbook.get_sample_data('ada.png') as image_file: image = plt.imread(image_file) fig, ax = plt.subplots() ax.imshow(image) ax.axis('off') # clear x-axis and y-axis # And another image w, h = 512, 512 with cbook.get_sample_data('ct.raw.gz') as datafile: s = datafile.read() A = np.frombuffer(s, np.uint16).astype(float).reshape((w, h)) A /= A.max() fig, ax = plt.subplots() extent = (0, 25, 0, 25) im = ax.imshow(A, cmap=plt.cm.hot, origin='upper', extent=extent) markers = [(15.9, 14.5), (16.8, 15)] x, y = zip(*markers) ax.plot(x, y, 'o') ax.set_title('CT density') plt.show() ############################################################################### # Interpolating images # -------------------- # # It is also possible to interpolate images before displaying them. Be careful, # as this may manipulate the way your data looks, but it can be helpful for # achieving the look you want. Below we'll display the same (small) array, # interpolated with three different interpolation methods. # # The center of the pixel at A[i,j] is plotted at i+0.5, i+0.5. If you # are using interpolation='nearest', the region bounded by (i,j) and # (i+1,j+1) will have the same color. If you are using interpolation, # the pixel center will have the same color as it does with nearest, but # other pixels will be interpolated between the neighboring pixels. # # To prevent edge effects when doing interpolation, Matplotlib pads the input # array with identical pixels around the edge: if you have a 5x5 array with # colors a-y as below:: # # a b c d e # f g h i j # k l m n o # p q r s t # u v w x y # # Matplotlib computes the interpolation and resizing on the padded array :: # # a a b c d e e # a a b c d e e # f f g h i j j # k k l m n o o # p p q r s t t # o u v w x y y # o u v w x y y # # and then extracts the central region of the result. (Extremely old versions # of Matplotlib (<0.63) did not pad the array, but instead adjusted the view # limits to hide the affected edge areas.) # # This approach allows plotting the full extent of an array without # edge effects, and for example to layer multiple images of different # sizes over one another with different interpolation methods -- see # :doc:`/gallery/images_contours_and_fields/layer_images`. It also implies # a performance hit, as this new temporary, padded array must be created. # Sophisticated interpolation also implies a performance hit; for maximal # performance or very large images, interpolation='nearest' is suggested. A = np.random.rand(5, 5) fig, axs = plt.subplots(1, 3, figsize=(10, 3)) for ax, interp in zip(axs, ['nearest', 'bilinear', 'bicubic']): ax.imshow(A, interpolation=interp) ax.set_title(interp.capitalize()) ax.grid(True) plt.show() ############################################################################### # You can specify whether images should be plotted with the array origin # x[0,0] in the upper left or lower right by using the origin parameter. # You can also control the default setting image.origin in your # :ref:`matplotlibrc file <customizing-with-matplotlibrc-files>`. For more on # this topic see the :doc:`complete guide on origin and extent # </tutorials/intermediate/imshow_extent>`. x = np.arange(120).reshape((10, 12)) interp = 'bilinear' fig, axs = plt.subplots(nrows=2, sharex=True, figsize=(3, 5)) axs[0].set_title('blue should be up') axs[0].imshow(x, origin='upper', interpolation=interp) axs[1].set_title('blue should be down') axs[1].imshow(x, origin='lower', interpolation=interp) plt.show() ############################################################################### # Finally, we'll show an image using a clip path. delta = 0.025 x = y = np.arange(-3.0, 3.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 path = Path([[0, 1], [1, 0], [0, -1], [-1, 0], [0, 1]]) patch = PathPatch(path, facecolor='none') fig, ax = plt.subplots() ax.add_patch(patch) im = ax.imshow(Z, interpolation='bilinear', cmap=cm.gray, origin='lower', extent=[-3, 3, -3, 3], clip_path=patch, clip_on=True) im.set_clip_path(patch) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown # in this example: import matplotlib matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.artist.Artist.set_clip_path matplotlib.patches.PathPatch
106ed7f9494bb7e829bc22489d1bb622ddaf297c21fdec162275953dcf262778
""" ============== Triinterp Demo ============== Interpolation from triangular grid to quad grid. """ import matplotlib.pyplot as plt import matplotlib.tri as mtri import numpy as np # Create triangulation. x = np.asarray([0, 1, 2, 3, 0.5, 1.5, 2.5, 1, 2, 1.5]) y = np.asarray([0, 0, 0, 0, 1.0, 1.0, 1.0, 2, 2, 3.0]) triangles = [[0, 1, 4], [1, 2, 5], [2, 3, 6], [1, 5, 4], [2, 6, 5], [4, 5, 7], [5, 6, 8], [5, 8, 7], [7, 8, 9]] triang = mtri.Triangulation(x, y, triangles) # Interpolate to regularly-spaced quad grid. z = np.cos(1.5 * x) * np.cos(1.5 * y) xi, yi = np.meshgrid(np.linspace(0, 3, 20), np.linspace(0, 3, 20)) interp_lin = mtri.LinearTriInterpolator(triang, z) zi_lin = interp_lin(xi, yi) interp_cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom') zi_cubic_geom = interp_cubic_geom(xi, yi) interp_cubic_min_E = mtri.CubicTriInterpolator(triang, z, kind='min_E') zi_cubic_min_E = interp_cubic_min_E(xi, yi) # Set up the figure fig, axs = plt.subplots(nrows=2, ncols=2) axs = axs.flatten() # Plot the triangulation. axs[0].tricontourf(triang, z) axs[0].triplot(triang, 'ko-') axs[0].set_title('Triangular grid') # Plot linear interpolation to quad grid. axs[1].contourf(xi, yi, zi_lin) axs[1].plot(xi, yi, 'k-', lw=0.5, alpha=0.5) axs[1].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5) axs[1].set_title("Linear interpolation") # Plot cubic interpolation to quad grid, kind=geom axs[2].contourf(xi, yi, zi_cubic_geom) axs[2].plot(xi, yi, 'k-', lw=0.5, alpha=0.5) axs[2].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5) axs[2].set_title("Cubic interpolation,\nkind='geom'") # Plot cubic interpolation to quad grid, kind=min_E axs[3].contourf(xi, yi, zi_cubic_min_E) axs[3].plot(xi, yi, 'k-', lw=0.5, alpha=0.5) axs[3].plot(xi.T, yi.T, 'k-', lw=0.5, alpha=0.5) axs[3].set_title("Cubic interpolation,\nkind='min_E'") fig.tight_layout() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.tricontourf matplotlib.pyplot.tricontourf matplotlib.axes.Axes.triplot matplotlib.pyplot.triplot matplotlib.axes.Axes.contourf matplotlib.pyplot.contourf matplotlib.axes.Axes.plot matplotlib.pyplot.plot matplotlib.tri matplotlib.tri.LinearTriInterpolator matplotlib.tri.CubicTriInterpolator matplotlib.tri.Triangulation
84f25071a438834748f52c4aa74c7aa7503092e23c2ec53547780dbaa33fe949
""" =========== Pcolor Demo =========== Generating images with :meth:`~.axes.Axes.pcolor`. Pcolor allows you to generate 2-D image-style plots. Below we will show how to do so in Matplotlib. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import LogNorm ############################################################################### # A simple pcolor demo # -------------------- Z = np.random.rand(6, 10) fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(Z) ax0.set_title('default: no edges') c = ax1.pcolor(Z, edgecolors='k', linewidths=4) ax1.set_title('thick edges') fig.tight_layout() plt.show() ############################################################################### # Comparing pcolor with similar functions # --------------------------------------- # # Demonstrates similarities between :meth:`~.axes.Axes.pcolor`, # :meth:`~.axes.Axes.pcolormesh`, :meth:`~.axes.Axes.imshow` and # :meth:`~.axes.Axes.pcolorfast` for drawing quadrilateral grids. # make these smaller to increase the resolution dx, dy = 0.15, 0.05 # generate 2 2d grids for the x & y bounds y, x = np.mgrid[slice(-3, 3 + dy, dy), slice(-3, 3 + dx, dx)] z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) # x and y are bounds, so z should be the value *inside* those bounds. # Therefore, remove the last value from the z array. z = z[:-1, :-1] z_min, z_max = -np.abs(z).max(), np.abs(z).max() fig, axs = plt.subplots(2, 2) ax = axs[0, 0] c = ax.pcolor(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max) ax.set_title('pcolor') # set the limits of the plot to the limits of the data ax.axis([x.min(), x.max(), y.min(), y.max()]) fig.colorbar(c, ax=ax) ax = axs[0, 1] c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max) ax.set_title('pcolormesh') # set the limits of the plot to the limits of the data ax.axis([x.min(), x.max(), y.min(), y.max()]) fig.colorbar(c, ax=ax) ax = axs[1, 0] c = ax.imshow(z, cmap='RdBu', vmin=z_min, vmax=z_max, extent=[x.min(), x.max(), y.min(), y.max()], interpolation='nearest', origin='lower') ax.set_title('image (nearest)') fig.colorbar(c, ax=ax) ax = axs[1, 1] c = ax.pcolorfast(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max) ax.set_title('pcolorfast') fig.colorbar(c, ax=ax) fig.tight_layout() plt.show() ############################################################################### # Pcolor with a log scale # ----------------------- # # The following shows pcolor plots with a log scale. N = 100 X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)] # A low hump with a spike coming out. # Needs to have z/colour axis on a log scale so we see both hump and spike. # linear scale only shows the spike. Z1 = np.exp(-(X)**2 - (Y)**2) Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) Z = Z1 + 50 * Z2 fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(X, Y, Z, norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap='PuBu_r') fig.colorbar(c, ax=ax0) c = ax1.pcolor(X, Y, Z, cmap='PuBu_r') fig.colorbar(c, ax=ax1) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.pcolor matplotlib.pyplot.pcolor matplotlib.axes.Axes.pcolormesh matplotlib.pyplot.pcolormesh matplotlib.axes.Axes.pcolorfast matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.colors.LogNorm
9ac09755bae07e16a2e4efac53b4c89762799811391d900e3cd84bc9c91ccb13
""" ============= Figimage Demo ============= This illustrates placing images directly in the figure, with no Axes objects. """ import numpy as np import matplotlib import matplotlib.pyplot as plt fig = plt.figure() Z = np.arange(10000).reshape((100, 100)) Z[:, 50:] = 1 im1 = fig.figimage(Z, xo=50, yo=0, origin='lower') im2 = fig.figimage(Z, xo=100, yo=100, alpha=.8, origin='lower') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: matplotlib.figure.Figure matplotlib.figure.Figure.figimage matplotlib.pyplot.figimage
2aed24af805451cd5f961e593e731b0804f1e4e0ba0c4d7ac816b7fc45053d81
""" ============================ Affine transform of an image ============================ Prepending an affine transformation (:class:`~.transforms.Affine2D`) to the :ref:`data transform <data-coords>` of an image allows to manipulate the image's shape and orientation. This is an example of the concept of :ref:`transform chaining <transformation-pipeline>`. For the backends that support draw_image with optional affine transform (e.g., agg, ps backend), the image of the output should have its boundary match the dashed yellow rectangle. """ import numpy as np import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms def get_image(): delta = 0.25 x = y = np.arange(-3.0, 3.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) return Z def do_plot(ax, Z, transform): im = ax.imshow(Z, interpolation='none', origin='lower', extent=[-2, 4, -3, 2], clip_on=True) trans_data = transform + ax.transData im.set_transform(trans_data) # display intended extent of the image x1, x2, y1, y2 = im.get_extent() ax.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], "y--", transform=trans_data) ax.set_xlim(-5, 5) ax.set_ylim(-4, 4) # prepare image and figure fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) Z = get_image() # image rotation do_plot(ax1, Z, mtransforms.Affine2D().rotate_deg(30)) # image skew do_plot(ax2, Z, mtransforms.Affine2D().skew_deg(30, 15)) # scale and reflection do_plot(ax3, Z, mtransforms.Affine2D().scale(-1, .5)) # everything and a translation do_plot(ax4, Z, mtransforms.Affine2D(). rotate_deg(30).skew_deg(30, 15).scale(-1, .5).translate(.5, -1)) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.transforms.Affine2D
41d4ac0b23ab4c3535f4dc3cb6152cdf4f25f0be0b3d966976280a75fd246b4d
""" ======================================================== Demonstration of advanced quiver and quiverkey functions ======================================================== Demonstrates some more advanced options for `~.axes.Axes.quiver`. For a simple example refer to :doc:`/gallery/images_contours_and_fields/quiver_simple_demo`. Known problem: the plot autoscaling does not take into account the arrows, so those on the boundaries are often out of the picture. This is *not* an easy problem to solve in a perfectly general way. The workaround is to manually expand the Axes objects. """ import matplotlib.pyplot as plt import numpy as np X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2)) U = np.cos(X) V = np.sin(Y) ############################################################################### fig1, ax1 = plt.subplots() ax1.set_title('Arrows scale with plot width, not view') Q = ax1.quiver(X, Y, U, V, units='width') qk = ax1.quiverkey(Q, 0.9, 0.9, 2, r'$2 \frac{m}{s}$', labelpos='E', coordinates='figure') ############################################################################### fig2, ax2 = plt.subplots() ax2.set_title("pivot='mid'; every third arrow; units='inches'") Q = ax2.quiver(X[::3, ::3], Y[::3, ::3], U[::3, ::3], V[::3, ::3], pivot='mid', units='inches') qk = ax2.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E', coordinates='figure') ax2.scatter(X[::3, ::3], Y[::3, ::3], color='r', s=5) ############################################################################### fig3, ax3 = plt.subplots() ax3.set_title("pivot='tip'; scales with x view") M = np.hypot(U, V) Q = ax3.quiver(X, Y, U, V, M, units='x', pivot='tip', width=0.022, scale=1 / 0.15) qk = ax3.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E', coordinates='figure') ax3.scatter(X, Y, color='k', s=5) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown in this example: import matplotlib matplotlib.axes.Axes.quiver matplotlib.pyplot.quiver matplotlib.axes.Axes.quiverkey matplotlib.pyplot.quiverkey
ab745bcfad6efbe24a301b2c41eb66aa1833c4e50fa97290707a144b3ca17028
""" ========================== Tricontour Smooth Delaunay ========================== Demonstrates high-resolution tricontouring of a random set of points; a `matplotlib.tri.TriAnalyzer` is used to improve the plot quality. The initial data points and triangular grid for this demo are: - a set of random points is instantiated, inside [-1, 1] x [-1, 1] square - A Delaunay triangulation of these points is then computed, of which a random subset of triangles is masked out by the user (based on *init_mask_frac* parameter). This simulates invalidated data. The proposed generic procedure to obtain a high resolution contouring of such a data set is the following: 1. Compute an extended mask with a `matplotlib.tri.TriAnalyzer`, which will exclude badly shaped (flat) triangles from the border of the triangulation. Apply the mask to the triangulation (using set_mask). 2. Refine and interpolate the data using a `matplotlib.tri.UniformTriRefiner`. 3. Plot the refined data with `~.axes.Axes.tricontour`. """ from matplotlib.tri import Triangulation, TriAnalyzer, UniformTriRefiner import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np #----------------------------------------------------------------------------- # Analytical test function #----------------------------------------------------------------------------- def experiment_res(x, y): """An analytic function representing experiment results.""" x = 2 * x r1 = np.sqrt((0.5 - x)**2 + (0.5 - y)**2) theta1 = np.arctan2(0.5 - x, 0.5 - y) r2 = np.sqrt((-x - 0.2)**2 + (-y - 0.2)**2) theta2 = np.arctan2(-x - 0.2, -y - 0.2) z = (4 * (np.exp((r1/10)**2) - 1) * 30 * np.cos(3 * theta1) + (np.exp((r2/10)**2) - 1) * 30 * np.cos(5 * theta2) + 2 * (x**2 + y**2)) return (np.max(z) - z) / (np.max(z) - np.min(z)) #----------------------------------------------------------------------------- # Generating the initial data test points and triangulation for the demo #----------------------------------------------------------------------------- # User parameters for data test points n_test = 200 # Number of test data points, tested from 3 to 5000 for subdiv=3 subdiv = 3 # Number of recursive subdivisions of the initial mesh for smooth # plots. Values >3 might result in a very high number of triangles # for the refine mesh: new triangles numbering = (4**subdiv)*ntri init_mask_frac = 0.0 # Float > 0. adjusting the proportion of # (invalid) initial triangles which will be masked # out. Enter 0 for no mask. min_circle_ratio = .01 # Minimum circle ratio - border triangles with circle # ratio below this will be masked if they touch a # border. Suggested value 0.01; use -1 to keep # all triangles. # Random points random_gen = np.random.RandomState(seed=19680801) x_test = random_gen.uniform(-1., 1., size=n_test) y_test = random_gen.uniform(-1., 1., size=n_test) z_test = experiment_res(x_test, y_test) # meshing with Delaunay triangulation tri = Triangulation(x_test, y_test) ntri = tri.triangles.shape[0] # Some invalid data are masked out mask_init = np.zeros(ntri, dtype=bool) masked_tri = random_gen.randint(0, ntri, int(ntri * init_mask_frac)) mask_init[masked_tri] = True tri.set_mask(mask_init) #----------------------------------------------------------------------------- # Improving the triangulation before high-res plots: removing flat triangles #----------------------------------------------------------------------------- # masking badly shaped triangles at the border of the triangular mesh. mask = TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio) tri.set_mask(mask) # refining the data refiner = UniformTriRefiner(tri) tri_refi, z_test_refi = refiner.refine_field(z_test, subdiv=subdiv) # analytical 'results' for comparison z_expected = experiment_res(tri_refi.x, tri_refi.y) # for the demo: loading the 'flat' triangles for plot flat_tri = Triangulation(x_test, y_test) flat_tri.set_mask(~mask) #----------------------------------------------------------------------------- # Now the plots #----------------------------------------------------------------------------- # User options for plots plot_tri = True # plot of base triangulation plot_masked_tri = True # plot of excessively flat excluded triangles plot_refi_tri = False # plot of refined triangulation plot_expected = False # plot of analytical function values for comparison # Graphical options for tricontouring levels = np.arange(0., 1., 0.025) cmap = cm.get_cmap(name='Blues', lut=None) fig, ax = plt.subplots() ax.set_aspect('equal') ax.set_title("Filtering a Delaunay mesh\n" + "(application to high-resolution tricontouring)") # 1) plot of the refined (computed) data contours: ax.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap, linewidths=[2.0, 0.5, 1.0, 0.5]) # 2) plot of the expected (analytical) data contours (dashed): if plot_expected: ax.tricontour(tri_refi, z_expected, levels=levels, cmap=cmap, linestyles='--') # 3) plot of the fine mesh on which interpolation was done: if plot_refi_tri: ax.triplot(tri_refi, color='0.97') # 4) plot of the initial 'coarse' mesh: if plot_tri: ax.triplot(tri, color='0.7') # 4) plot of the unvalidated triangles from naive Delaunay Triangulation: if plot_masked_tri: ax.triplot(flat_tri, color='red') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.tricontour matplotlib.pyplot.tricontour matplotlib.axes.Axes.tricontourf matplotlib.pyplot.tricontourf matplotlib.axes.Axes.triplot matplotlib.pyplot.triplot matplotlib.tri matplotlib.tri.Triangulation matplotlib.tri.TriAnalyzer matplotlib.tri.UniformTriRefiner
142f3e72e0d1dbe8aaf6caa17b32c5ce49e34049ae21230878a48540b75b9250
""" ============ Triplot Demo ============ Creating and plotting unstructured triangular grids. """ import matplotlib.pyplot as plt import matplotlib.tri as tri import numpy as np ############################################################################### # Creating a Triangulation without specifying the triangles results in the # Delaunay triangulation of the points. # First create the x and y coordinates of the points. n_angles = 36 n_radii = 8 min_radius = 0.25 radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi / n_angles x = (radii * np.cos(angles)).flatten() y = (radii * np.sin(angles)).flatten() # Create the Triangulation; no triangles so Delaunay triangulation created. triang = tri.Triangulation(x, y) # Mask off unwanted triangles. triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < min_radius) ############################################################################### # Plot the triangulation. fig1, ax1 = plt.subplots() ax1.set_aspect('equal') ax1.triplot(triang, 'bo-', lw=1) ax1.set_title('triplot of Delaunay triangulation') ############################################################################### # You can specify your own triangulation rather than perform a Delaunay # triangulation of the points, where each triangle is given by the indices of # the three points that make up the triangle, ordered in either a clockwise or # anticlockwise manner. xy = np.asarray([ [-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890], [-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898], [-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919], [-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942], [-0.062, 0.949], [-0.054, 0.958], [-0.069, 0.954], [-0.087, 0.952], [-0.087, 0.959], [-0.080, 0.966], [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965], [-0.097, 0.975], [-0.092, 0.984], [-0.101, 0.980], [-0.108, 0.980], [-0.104, 0.987], [-0.102, 0.993], [-0.115, 1.001], [-0.099, 0.996], [-0.101, 1.007], [-0.090, 1.010], [-0.087, 1.021], [-0.069, 1.021], [-0.052, 1.022], [-0.052, 1.017], [-0.069, 1.010], [-0.064, 1.005], [-0.048, 1.005], [-0.031, 1.005], [-0.031, 0.996], [-0.040, 0.987], [-0.045, 0.980], [-0.052, 0.975], [-0.040, 0.973], [-0.026, 0.968], [-0.020, 0.954], [-0.006, 0.947], [ 0.003, 0.935], [ 0.006, 0.926], [ 0.005, 0.921], [ 0.022, 0.923], [ 0.033, 0.912], [ 0.029, 0.905], [ 0.017, 0.900], [ 0.012, 0.895], [ 0.027, 0.893], [ 0.019, 0.886], [ 0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879], [-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872], [-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933], [-0.077, 0.990], [-0.059, 0.993]]) x = np.degrees(xy[:, 0]) y = np.degrees(xy[:, 1]) triangles = np.asarray([ [67, 66, 1], [65, 2, 66], [ 1, 66, 2], [64, 2, 65], [63, 3, 64], [60, 59, 57], [ 2, 64, 3], [ 3, 63, 4], [ 0, 67, 1], [62, 4, 63], [57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [ 4, 62, 68], [ 6, 5, 9], [61, 68, 62], [69, 68, 61], [ 9, 5, 70], [ 6, 8, 7], [ 4, 70, 5], [ 8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9], [54, 53, 55], [56, 55, 53], [68, 70, 4], [52, 56, 53], [11, 10, 12], [69, 71, 68], [68, 13, 70], [10, 70, 13], [51, 50, 52], [13, 68, 71], [52, 71, 69], [12, 10, 13], [71, 52, 50], [71, 14, 13], [50, 49, 71], [49, 48, 71], [14, 16, 15], [14, 71, 48], [17, 19, 18], [17, 20, 19], [48, 16, 14], [48, 47, 16], [47, 46, 16], [16, 46, 45], [23, 22, 24], [21, 24, 22], [17, 16, 45], [20, 17, 45], [21, 25, 24], [27, 26, 28], [20, 72, 21], [25, 21, 72], [45, 72, 20], [25, 28, 26], [44, 73, 45], [72, 45, 73], [28, 25, 29], [29, 25, 31], [43, 73, 44], [73, 43, 40], [72, 73, 39], [72, 31, 25], [42, 40, 43], [31, 30, 29], [39, 73, 40], [42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38], [33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]]) ############################################################################### # Rather than create a Triangulation object, can simply pass x, y and triangles # arrays to triplot directly. It would be better to use a Triangulation object # if the same triangulation was to be used more than once to save duplicated # calculations. fig2, ax2 = plt.subplots() ax2.set_aspect('equal') ax2.triplot(x, y, triangles, 'go-', lw=1.0) ax2.set_title('triplot of user-specified triangulation') ax2.set_xlabel('Longitude (degrees)') ax2.set_ylabel('Latitude (degrees)') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.triplot matplotlib.pyplot.triplot matplotlib.tri matplotlib.tri.Triangulation
aabc84611a648c5dc5ad21615eadd97f4b1bae9e99f61f1f7af295e74da59097
""" ================== Contour Label Demo ================== Illustrate some of the more advanced things that one can do with contour labels. See also the :doc:`contour demo example </gallery/images_contours_and_fields/contour_demo>`. """ import matplotlib import numpy as np import matplotlib.ticker as ticker import matplotlib.pyplot as plt ############################################################################### # Define our surface 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 ############################################################################### # Make contour labels using creative float classes # Follows suggestion of Manuel Metz # Define a class that forces representation of float to look a certain way # This remove trailing zero so '1.0' becomes '1' class nf(float): def __repr__(self): s = f'{self:.1f}' return f'{self:.0f}' if s[-1] == '0' else s # Basic contour plot fig, ax = plt.subplots() CS = ax.contour(X, Y, Z) # Recast levels to new class CS.levels = [nf(val) for val in CS.levels] # Label levels with specially formatted floats if plt.rcParams["text.usetex"]: fmt = r'%r \%%' else: fmt = '%r %%' ax.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10) ############################################################################### # Label contours with arbitrary strings using a dictionary fig1, ax1 = plt.subplots() # Basic contour plot CS1 = ax1.contour(X, Y, Z) fmt = {} strs = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh'] for l, s in zip(CS1.levels, strs): fmt[l] = s # Label every other level using strings ax1.clabel(CS1, CS1.levels[::2], inline=True, fmt=fmt, fontsize=10) ############################################################################### # Use a Formatter fig2, ax2 = plt.subplots() CS2 = ax2.contour(X, Y, 100**Z, locator=plt.LogLocator()) fmt = ticker.LogFormatterMathtext() fmt.create_dummy_axis() ax2.clabel(CS2, CS2.levels, fmt=fmt) ax2.set_title("$100^Z$") plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: matplotlib.axes.Axes.contour matplotlib.pyplot.contour matplotlib.axes.Axes.clabel matplotlib.pyplot.clabel matplotlib.ticker.LogFormatterMathtext matplotlib.ticker.TickHelper.create_dummy_axis
401387442a4ec7cb7c9c95c58b8ae4227d3493a16f7a9dca9a952ae2dc4c45e9
""" ============= Contour Image ============= Test combinations of contouring, filled contouring, and image plotting. For contour labelling, see also the :doc:`contour demo example </gallery/images_contours_and_fields/contour_demo>`. The emphasis in this demo is on showing how to make contours register correctly on images, and on how to get both of them oriented as desired. In particular, note the usage of the :doc:`"origin" and "extent" </tutorials/intermediate/imshow_extent>` keyword arguments to imshow and contour. """ import matplotlib.pyplot as plt import numpy as np from matplotlib import cm # Default delta is large because that makes it fast, and it illustrates # the correct registration between image and contours. delta = 0.5 extent = (-3, 4, -4, 3) x = np.arange(-3.0, 4.001, delta) y = np.arange(-4.0, 3.001, 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 # Boost the upper limit to avoid truncation errors. levels = np.arange(-2.0, 1.601, 0.4) norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max()) cmap = cm.PRGn fig, _axs = plt.subplots(nrows=2, ncols=2) fig.subplots_adjust(hspace=0.3) axs = _axs.flatten() cset1 = axs[0].contourf(X, Y, Z, levels, norm=norm, cmap=cm.get_cmap(cmap, len(levels) - 1)) # It is not necessary, but for the colormap, we need only the # number of levels minus 1. To avoid discretization error, use # either this number or a large number such as the default (256). # If we want lines as well as filled regions, we need to call # contour separately; don't try to change the edgecolor or edgewidth # of the polygons in the collections returned by contourf. # Use levels output from previous call to guarantee they are the same. cset2 = axs[0].contour(X, Y, Z, cset1.levels, colors='k') # We don't really need dashed contour lines to indicate negative # regions, so let's turn them off. for c in cset2.collections: c.set_linestyle('solid') # It is easier here to make a separate call to contour than # to set up an array of colors and linewidths. # We are making a thick green line as a zero contour. # Specify the zero level as a tuple with only 0 in it. cset3 = axs[0].contour(X, Y, Z, (0,), colors='g', linewidths=2) axs[0].set_title('Filled contours') fig.colorbar(cset1, ax=axs[0]) axs[1].imshow(Z, extent=extent, cmap=cmap, norm=norm) axs[1].contour(Z, levels, colors='k', origin='upper', extent=extent) axs[1].set_title("Image, origin 'upper'") axs[2].imshow(Z, origin='lower', extent=extent, cmap=cmap, norm=norm) axs[2].contour(Z, levels, colors='k', origin='lower', extent=extent) axs[2].set_title("Image, origin 'lower'") # We will use the interpolation "nearest" here to show the actual # image pixels. # Note that the contour lines don't extend to the edge of the box. # This is intentional. The Z values are defined at the center of each # image pixel (each color block on the following subplot), so the # domain that is contoured does not extend beyond these pixel centers. im = axs[3].imshow(Z, interpolation='nearest', extent=extent, cmap=cmap, norm=norm) axs[3].contour(Z, levels, colors='k', origin='image', extent=extent) ylim = axs[3].get_ylim() axs[3].set_ylim(ylim[::-1]) axs[3].set_title("Origin from rc, reversed y-axis") fig.colorbar(im, ax=axs[3]) fig.tight_layout() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.contour matplotlib.pyplot.contour matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.colors.Normalize
b19ff180f2a68875ffd5924aa8d8be51f615f1727d92a27df557eaed485970df
""" =========================================== Blend transparency with color in 2-D images =========================================== Blend transparency with color to highlight parts of data with imshow. A common use for :func:`matplotlib.pyplot.imshow` is to plot a 2-D statistical map. While ``imshow`` makes it easy to visualize a 2-D matrix as an image, it doesn't easily let you add transparency to the output. For example, one can plot a statistic (such as a t-statistic) and color the transparency of each pixel according to its p-value. This example demonstrates how you can achieve this effect using :class:`matplotlib.colors.Normalize`. Note that it is not possible to directly pass alpha values to :func:`matplotlib.pyplot.imshow`. First we will generate some data, in this case, we'll create two 2-D "blobs" in a 2-D grid. One blob will be positive, and the other negative. """ # sphinx_gallery_thumbnail_number = 3 import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import Normalize def normal_pdf(x, mean, var): return np.exp(-(x - mean)**2 / (2*var)) # Generate the space in which the blobs will live xmin, xmax, ymin, ymax = (0, 100, 0, 100) n_bins = 100 xx = np.linspace(xmin, xmax, n_bins) yy = np.linspace(ymin, ymax, n_bins) # Generate the blobs. The range of the values is roughly -.0002 to .0002 means_high = [20, 50] means_low = [50, 60] var = [150, 200] gauss_x_high = normal_pdf(xx, means_high[0], var[0]) gauss_y_high = normal_pdf(yy, means_high[1], var[0]) gauss_x_low = normal_pdf(xx, means_low[0], var[1]) gauss_y_low = normal_pdf(yy, means_low[1], var[1]) weights = (np.outer(gauss_y_high, gauss_x_high) - np.outer(gauss_y_low, gauss_x_low)) # We'll also create a grey background into which the pixels will fade greys = np.full((*weights.shape, 3), 70, dtype=np.uint8) # First we'll plot these blobs using only ``imshow``. vmax = np.abs(weights).max() vmin = -vmax cmap = plt.cm.RdYlBu fig, ax = plt.subplots() ax.imshow(greys) ax.imshow(weights, extent=(xmin, xmax, ymin, ymax), cmap=cmap) ax.set_axis_off() ############################################################################### # Blending in transparency # ======================== # # The simplest way to include transparency when plotting data with # :func:`matplotlib.pyplot.imshow` is to convert the 2-D data array to a # 3-D image array of rgba values. This can be done with # :class:`matplotlib.colors.Normalize`. For example, we'll create a gradient # moving from left to right below. # Create an alpha channel of linearly increasing values moving to the right. alphas = np.ones(weights.shape) alphas[:, 30:] = np.linspace(1, 0, 70) # Normalize the colors b/w 0 and 1, we'll then pass an MxNx4 array to imshow colors = Normalize(vmin, vmax, clip=True)(weights) colors = cmap(colors) # Now set the alpha channel to the one we created above colors[..., -1] = alphas # Create the figure and image # Note that the absolute values may be slightly different fig, ax = plt.subplots() ax.imshow(greys) ax.imshow(colors, extent=(xmin, xmax, ymin, ymax)) ax.set_axis_off() ############################################################################### # Using transparency to highlight values with high amplitude # ========================================================== # # Finally, we'll recreate the same plot, but this time we'll use transparency # to highlight the extreme values in the data. This is often used to highlight # data points with smaller p-values. We'll also add in contour lines to # highlight the image values. # Create an alpha channel based on weight values # Any value whose absolute value is > .0001 will have zero transparency alphas = Normalize(0, .3, clip=True)(np.abs(weights)) alphas = np.clip(alphas, .4, 1) # alpha value clipped at the bottom at .4 # Normalize the colors b/w 0 and 1, we'll then pass an MxNx4 array to imshow colors = Normalize(vmin, vmax)(weights) colors = cmap(colors) # Now set the alpha channel to the one we created above colors[..., -1] = alphas # Create the figure and image # Note that the absolute values may be slightly different fig, ax = plt.subplots() ax.imshow(greys) ax.imshow(colors, extent=(xmin, xmax, ymin, ymax)) # Add contour lines to further highlight different levels. ax.contour(weights[::-1], levels=[-.1, .1], colors='k', linestyles='-') ax.set_axis_off() plt.show() ax.contour(weights[::-1], levels=[-.0001, .0001], colors='k', linestyles='-') ax.set_axis_off() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.axes.Axes.contour matplotlib.pyplot.contour matplotlib.colors.Normalize matplotlib.axes.Axes.set_axis_off
ea2c8b968915e0dd061920a5cd5ec60b57eca9c17dac6b792b28cb7f42e63a7d
""" =================== Contour Corner Mask =================== Illustrate the difference between ``corner_mask=False`` and ``corner_mask=True`` for masked contour plots. """ import matplotlib.pyplot as plt import numpy as np # Data to plot. x, y = np.meshgrid(np.arange(7), np.arange(10)) z = np.sin(0.5 * x) * np.cos(0.52 * y) # Mask various z values. mask = np.zeros_like(z, dtype=bool) mask[2, 3:5] = True mask[3:5, 4] = True mask[7, 2] = True mask[5, 0] = True mask[0, 6] = True z = np.ma.array(z, mask=mask) corner_masks = [False, True] fig, axs = plt.subplots(ncols=2) for ax, corner_mask in zip(axs, corner_masks): cs = ax.contourf(x, y, z, corner_mask=corner_mask) ax.contour(cs, colors='k') ax.set_title('corner_mask = {0}'.format(corner_mask)) # Plot grid. ax.grid(c='k', ls='-', alpha=0.3) # Indicate masked points with red circles. ax.plot(np.ma.array(x, mask=~mask), y, 'ro') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown # in this example: import matplotlib matplotlib.axes.Axes.contour matplotlib.pyplot.contour matplotlib.axes.Axes.contourf matplotlib.pyplot.contourf
2103c75f5c716c550644d6a64b6702be44bb6d31e834fdf2eceefcdd81d97585
""" ============ Image Masked ============ imshow with masked array input and out-of-range colors. The second subplot illustrates the use of BoundaryNorm to get a filled contour effect. """ from copy import copy import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors # compute some interesting data x0, x1 = -5, 5 y0, y1 = -3, 3 x = np.linspace(x0, x1, 500) y = np.linspace(y0, y1, 500) 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 # Set up a colormap: # use copy so that we do not mutate the global colormap instance palette = copy(plt.cm.gray) palette.set_over('r', 1.0) palette.set_under('g', 1.0) palette.set_bad('b', 1.0) # Alternatively, we could use # palette.set_bad(alpha = 0.0) # to make the bad region transparent. This is the default. # If you comment out all the palette.set* lines, you will see # all the defaults; under and over will be colored with the # first and last colors in the palette, respectively. Zm = np.ma.masked_where(Z > 1.2, Z) # By setting vmin and vmax in the norm, we establish the # range to which the regular palette color scale is applied. # Anything above that range is colored based on palette.set_over, etc. # set up the Axes objects fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(6, 5.4)) # plot using 'continuous' color map im = ax1.imshow(Zm, interpolation='bilinear', cmap=palette, norm=colors.Normalize(vmin=-1.0, vmax=1.0), aspect='auto', origin='lower', extent=[x0, x1, y0, y1]) ax1.set_title('Green=low, Red=high, Blue=masked') cbar = fig.colorbar(im, extend='both', shrink=0.9, ax=ax1) cbar.set_label('uniform') for ticklabel in ax1.xaxis.get_ticklabels(): ticklabel.set_visible(False) # Plot using a small number of colors, with unevenly spaced boundaries. im = ax2.imshow(Zm, interpolation='nearest', cmap=palette, norm=colors.BoundaryNorm([-1, -0.5, -0.2, 0, 0.2, 0.5, 1], ncolors=palette.N), aspect='auto', origin='lower', extent=[x0, x1, y0, y1]) ax2.set_title('With BoundaryNorm') cbar = fig.colorbar(im, extend='both', spacing='proportional', shrink=0.9, ax=ax2) cbar.set_label('proportional') fig.suptitle('imshow, with out-of-range and masked data') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown # in this example: import matplotlib matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.colors.BoundaryNorm matplotlib.colorbar.ColorbarBase.set_label
acf39e61d53035c0bb2c81ccd88f1386b0bd46b0185f56fe380a494b63dcce45
""" ======= Matshow ======= Simple `~.axes.Axes.matshow` example. """ import matplotlib.pyplot as plt import numpy as np def samplemat(dims): """Make a matrix with all zeros and increasing elements on the diagonal""" aa = np.zeros(dims) for i in range(min(dims)): aa[i, i] = i return aa # Display matrix plt.matshow(samplemat((15, 15))) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown # in this example: import matplotlib matplotlib.axes.Axes.matshow matplotlib.pyplot.matshow
f1093189bb1563af354482661a8a97a1aef3df0b6e3cb43d196b53a10d56f868
""" =========== Multi Image =========== Make a set of images with a single colormap, norm, and colorbar. """ from matplotlib import colors import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) Nr = 3 Nc = 2 cmap = "cool" fig, axs = plt.subplots(Nr, Nc) fig.suptitle('Multiple images') images = [] for i in range(Nr): for j in range(Nc): # Generate data with a range that varies from one plot to the next. data = ((1 + i + j) / 10) * np.random.rand(10, 20) * 1e-6 images.append(axs[i, j].imshow(data, cmap=cmap)) axs[i, j].label_outer() # Find the min and max of all colors for use in setting the color scale. vmin = min(image.get_array().min() for image in images) vmax = max(image.get_array().max() for image in images) norm = colors.Normalize(vmin=vmin, vmax=vmax) for im in images: im.set_norm(norm) fig.colorbar(images[0], ax=axs, orientation='horizontal', fraction=.1) # Make images respond to changes in the norm of other images (e.g. via the # "edit axis, curves and images parameters" GUI on Qt), but be careful not to # recurse infinitely! def update(changed_image): for im in images: if (changed_image.get_cmap() != im.get_cmap() or changed_image.get_clim() != im.get_clim()): im.set_cmap(changed_image.get_cmap()) im.set_clim(changed_image.get_clim()) for im in images: im.callbacksSM.connect('changed', update) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.colors.Normalize matplotlib.cm.ScalarMappable.set_cmap matplotlib.cm.ScalarMappable.set_norm matplotlib.cm.ScalarMappable.set_clim matplotlib.cbook.CallbackRegistry.connect
ad954e95bf178a826be87fec8bb239cef2e3face55c0ca6a9efd76e5a71c769f
""" ============== Tripcolor Demo ============== Pseudocolor plots of unstructured triangular grids. """ import matplotlib.pyplot as plt import matplotlib.tri as tri import numpy as np ############################################################################### # Creating a Triangulation without specifying the triangles results in the # Delaunay triangulation of the points. # First create the x and y coordinates of the points. n_angles = 36 n_radii = 8 min_radius = 0.25 radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi / n_angles x = (radii * np.cos(angles)).flatten() y = (radii * np.sin(angles)).flatten() z = (np.cos(radii) * np.cos(3 * angles)).flatten() # Create the Triangulation; no triangles so Delaunay triangulation created. triang = tri.Triangulation(x, y) # Mask off unwanted triangles. triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < min_radius) ############################################################################### # tripcolor plot. fig1, ax1 = plt.subplots() ax1.set_aspect('equal') tpc = ax1.tripcolor(triang, z, shading='flat') fig1.colorbar(tpc) ax1.set_title('tripcolor of Delaunay triangulation, flat shading') ############################################################################### # Illustrate Gouraud shading. fig2, ax2 = plt.subplots() ax2.set_aspect('equal') tpc = ax2.tripcolor(triang, z, shading='gouraud') fig2.colorbar(tpc) ax2.set_title('tripcolor of Delaunay triangulation, gouraud shading') ############################################################################### # You can specify your own triangulation rather than perform a Delaunay # triangulation of the points, where each triangle is given by the indices of # the three points that make up the triangle, ordered in either a clockwise or # anticlockwise manner. xy = np.asarray([ [-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890], [-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898], [-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919], [-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942], [-0.062, 0.949], [-0.054, 0.958], [-0.069, 0.954], [-0.087, 0.952], [-0.087, 0.959], [-0.080, 0.966], [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965], [-0.097, 0.975], [-0.092, 0.984], [-0.101, 0.980], [-0.108, 0.980], [-0.104, 0.987], [-0.102, 0.993], [-0.115, 1.001], [-0.099, 0.996], [-0.101, 1.007], [-0.090, 1.010], [-0.087, 1.021], [-0.069, 1.021], [-0.052, 1.022], [-0.052, 1.017], [-0.069, 1.010], [-0.064, 1.005], [-0.048, 1.005], [-0.031, 1.005], [-0.031, 0.996], [-0.040, 0.987], [-0.045, 0.980], [-0.052, 0.975], [-0.040, 0.973], [-0.026, 0.968], [-0.020, 0.954], [-0.006, 0.947], [ 0.003, 0.935], [ 0.006, 0.926], [ 0.005, 0.921], [ 0.022, 0.923], [ 0.033, 0.912], [ 0.029, 0.905], [ 0.017, 0.900], [ 0.012, 0.895], [ 0.027, 0.893], [ 0.019, 0.886], [ 0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879], [-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872], [-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933], [-0.077, 0.990], [-0.059, 0.993]]) x, y = np.rad2deg(xy).T triangles = np.asarray([ [67, 66, 1], [65, 2, 66], [ 1, 66, 2], [64, 2, 65], [63, 3, 64], [60, 59, 57], [ 2, 64, 3], [ 3, 63, 4], [ 0, 67, 1], [62, 4, 63], [57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [ 4, 62, 68], [ 6, 5, 9], [61, 68, 62], [69, 68, 61], [ 9, 5, 70], [ 6, 8, 7], [ 4, 70, 5], [ 8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9], [54, 53, 55], [56, 55, 53], [68, 70, 4], [52, 56, 53], [11, 10, 12], [69, 71, 68], [68, 13, 70], [10, 70, 13], [51, 50, 52], [13, 68, 71], [52, 71, 69], [12, 10, 13], [71, 52, 50], [71, 14, 13], [50, 49, 71], [49, 48, 71], [14, 16, 15], [14, 71, 48], [17, 19, 18], [17, 20, 19], [48, 16, 14], [48, 47, 16], [47, 46, 16], [16, 46, 45], [23, 22, 24], [21, 24, 22], [17, 16, 45], [20, 17, 45], [21, 25, 24], [27, 26, 28], [20, 72, 21], [25, 21, 72], [45, 72, 20], [25, 28, 26], [44, 73, 45], [72, 45, 73], [28, 25, 29], [29, 25, 31], [43, 73, 44], [73, 43, 40], [72, 73, 39], [72, 31, 25], [42, 40, 43], [31, 30, 29], [39, 73, 40], [42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38], [33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]]) xmid = x[triangles].mean(axis=1) ymid = y[triangles].mean(axis=1) x0 = -5 y0 = 52 zfaces = np.exp(-0.01 * ((xmid - x0) * (xmid - x0) + (ymid - y0) * (ymid - y0))) ############################################################################### # Rather than create a Triangulation object, can simply pass x, y and triangles # arrays to tripcolor directly. It would be better to use a Triangulation # object if the same triangulation was to be used more than once to save # duplicated calculations. # Can specify one color value per face rather than one per point by using the # facecolors kwarg. fig3, ax3 = plt.subplots() ax3.set_aspect('equal') tpc = ax3.tripcolor(x, y, triangles, facecolors=zfaces, edgecolors='k') fig3.colorbar(tpc) ax3.set_title('tripcolor of user-specified triangulation') ax3.set_xlabel('Longitude (degrees)') ax3.set_ylabel('Latitude (degrees)') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.tripcolor matplotlib.pyplot.tripcolor matplotlib.tri matplotlib.tri.Triangulation
d5f7a1a639b93e7547823922ee13148209e2a5c9bcf6ef4884851c4b7f108f53
""" ====================== Tricontour Smooth User ====================== Demonstrates high-resolution tricontouring on user-defined triangular grids with `matplotlib.tri.UniformTriRefiner`. """ import matplotlib.tri as tri import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np #----------------------------------------------------------------------------- # Analytical test function #----------------------------------------------------------------------------- def function_z(x, y): r1 = np.sqrt((0.5 - x)**2 + (0.5 - y)**2) theta1 = np.arctan2(0.5 - x, 0.5 - y) r2 = np.sqrt((-x - 0.2)**2 + (-y - 0.2)**2) theta2 = np.arctan2(-x - 0.2, -y - 0.2) z = -(2 * (np.exp((r1 / 10)**2) - 1) * 30. * np.cos(7. * theta1) + (np.exp((r2 / 10)**2) - 1) * 30. * np.cos(11. * theta2) + 0.7 * (x**2 + y**2)) return (np.max(z) - z) / (np.max(z) - np.min(z)) #----------------------------------------------------------------------------- # Creating a Triangulation #----------------------------------------------------------------------------- # First create the x and y coordinates of the points. n_angles = 20 n_radii = 10 min_radius = 0.15 radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi / n_angles x = (radii * np.cos(angles)).flatten() y = (radii * np.sin(angles)).flatten() z = function_z(x, y) # Now create the Triangulation. # (Creating a Triangulation without specifying the triangles results in the # Delaunay triangulation of the points.) triang = tri.Triangulation(x, y) # Mask off unwanted triangles. triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < min_radius) #----------------------------------------------------------------------------- # Refine data #----------------------------------------------------------------------------- refiner = tri.UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(z, subdiv=3) #----------------------------------------------------------------------------- # Plot the triangulation and the high-res iso-contours #----------------------------------------------------------------------------- fig, ax = plt.subplots() ax.set_aspect('equal') ax.triplot(triang, lw=0.5, color='white') levels = np.arange(0., 1., 0.025) cmap = cm.get_cmap(name='terrain', lut=None) ax.tricontourf(tri_refi, z_test_refi, levels=levels, cmap=cmap) ax.tricontour(tri_refi, z_test_refi, levels=levels, colors=['0.25', '0.5', '0.5', '0.5', '0.5'], linewidths=[1.0, 0.5, 0.5, 0.5, 0.5]) ax.set_title("High-resolution tricontouring") plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.tricontour matplotlib.pyplot.tricontour matplotlib.axes.Axes.tricontourf matplotlib.pyplot.tricontourf matplotlib.tri matplotlib.tri.Triangulation matplotlib.tri.UniformTriRefiner
a9eb2459f6285b9baa8e57bacb223a6d32f1333636cbdec35354f66604389811
""" ================================= Interpolations for imshow/matshow ================================= This example displays the difference between interpolation methods for :meth:`~.axes.Axes.imshow` and :meth:`~.axes.Axes.matshow`. If `interpolation` is None, it defaults to the ``image.interpolation`` :doc:`rc parameter </tutorials/introductory/customizing>`. If the interpolation is ``'none'``, then no interpolation is performed for the Agg, ps and pdf backends. Other backends will default to ``'nearest'``. For the Agg, ps and pdf backends, ``interpolation = 'none'`` works well when a big image is scaled down, while ``interpolation = 'nearest'`` works well when a small image is scaled up. """ import matplotlib.pyplot as plt import numpy as np methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos'] # Fixing random state for reproducibility np.random.seed(19680801) grid = np.random.rand(4, 4) fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6), subplot_kw={'xticks': [], 'yticks': []}) for ax, interp_method in zip(axs.flat, methods): ax.imshow(grid, interpolation=interp_method, cmap='viridis') ax.set_title(str(interp_method)) plt.tight_layout() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown # in this example: import matplotlib matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow
f5a7df8c07a53b9f37ca6b171b4d67710febdebc366a192040e4f25f46a4cfb7
""" ======================================= Contour plot of irregularly spaced data ======================================= Comparison of a contour plot of irregularly spaced data interpolated on a regular grid versus a tricontour plot for an unstructured triangular grid. Since `~.axes.Axes.contour` and `~.axes.Axes.contourf` expect the data to live on a regular grid, plotting a contour plot of irregularly spaced data requires different methods. The two options are: * Interpolate the data to a regular grid first. This can be done with on-board means, e.g. via `~.tri.LinearTriInterpolator` or using external functionality e.g. via `scipy.interpolate.griddata`. Then plot the interpolated data with the usual `~.axes.Axes.contour`. * Directly use `~.axes.Axes.tricontour` or `~.axes.Axes.tricontourf` which will perform a triangulation internally. This example shows both methods in action. """ import matplotlib.pyplot as plt import matplotlib.tri as tri import numpy as np np.random.seed(19680801) npts = 200 ngridx = 100 ngridy = 200 x = np.random.uniform(-2, 2, npts) y = np.random.uniform(-2, 2, npts) z = x * np.exp(-x**2 - y**2) fig, (ax1, ax2) = plt.subplots(nrows=2) # ----------------------- # Interpolation on a grid # ----------------------- # A contour plot of irregularly spaced data coordinates # via interpolation on a grid. # Create grid values first. xi = np.linspace(-2.1, 2.1, ngridx) yi = np.linspace(-2.1, 2.1, ngridy) # Perform linear interpolation of the data (x,y) # on a grid defined by (xi,yi) triang = tri.Triangulation(x, y) interpolator = tri.LinearTriInterpolator(triang, z) Xi, Yi = np.meshgrid(xi, yi) zi = interpolator(Xi, Yi) # Note that scipy.interpolate provides means to interpolate data on a grid # as well. The following would be an alternative to the four lines above: #from scipy.interpolate import griddata #zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear') ax1.contour(xi, yi, zi, levels=14, linewidths=0.5, colors='k') cntr1 = ax1.contourf(xi, yi, zi, levels=14, cmap="RdBu_r") fig.colorbar(cntr1, ax=ax1) ax1.plot(x, y, 'ko', ms=3) ax1.axis((-2, 2, -2, 2)) ax1.set_title('grid and contour (%d points, %d grid points)' % (npts, ngridx * ngridy)) # ---------- # Tricontour # ---------- # Directly supply the unordered, irregularly spaced coordinates # to tricontour. ax2.tricontour(x, y, z, levels=14, linewidths=0.5, colors='k') cntr2 = ax2.tricontourf(x, y, z, levels=14, cmap="RdBu_r") fig.colorbar(cntr2, ax=ax2) ax2.plot(x, y, 'ko', ms=3) ax2.axis((-2, 2, -2, 2)) ax2.set_title('tricontour (%d points)' % npts) plt.subplots_adjust(hspace=0.5) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown in this example: import matplotlib matplotlib.axes.Axes.contour matplotlib.pyplot.contour matplotlib.axes.Axes.contourf matplotlib.pyplot.contourf matplotlib.axes.Axes.tricontour matplotlib.pyplot.tricontour matplotlib.axes.Axes.tricontourf matplotlib.pyplot.tricontourf
eb86f2d59ffb59aa252905fdaf5e655e7844f7cbe5232f14abb98dbd4ba04798
""" ========= Spy Demos ========= Plot the sparsity pattern of arrays. """ import matplotlib.pyplot as plt import numpy as np fig, axs = plt.subplots(2, 2) ax1 = axs[0, 0] ax2 = axs[0, 1] ax3 = axs[1, 0] ax4 = axs[1, 1] x = np.random.randn(20, 20) x[5, :] = 0. x[:, 12] = 0. ax1.spy(x, markersize=5) ax2.spy(x, precision=0.1, markersize=5) ax3.spy(x) ax4.spy(x, precision=0.1) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.spy matplotlib.pyplot.spy
589e0d010654564ec4360fe36d7c7f4315b5741d653f35aeb31466cc57385db6
""" ================================== Modifying the coordinate formatter ================================== Modify the coordinate formatter to report the image "z" value of the nearest pixel given x and y. This functionality is built in by default, but it is still useful to show how to customize the `~.axes.Axes.format_coord` function. """ import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) X = 10*np.random.rand(5, 3) fig, ax = plt.subplots() ax.imshow(X, interpolation='nearest') numrows, numcols = X.shape def format_coord(x, y): col = int(x + 0.5) row = int(y + 0.5) if col >= 0 and col < numcols and row >= 0 and row < numrows: z = X[row, col] return 'x=%1.4f, y=%1.4f, z=%1.4f' % (x, y, z) else: return 'x=%1.4f, y=%1.4f' % (x, y) ax.format_coord = format_coord plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.format_coord matplotlib.axes.Axes.imshow
076a57c88373f3eee44d78526656d84bccae17c0c0854cd8455b7544de23eba1
""" ============= Contourf Demo ============= How to use the :meth:`.axes.Axes.contourf` method to create filled contour plots. """ import numpy as np import matplotlib.pyplot as plt origin = 'lower' delta = 0.025 x = y = np.arange(-3.0, 3.01, 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 nr, nc = Z.shape # put NaNs in one corner: Z[-nr // 6:, -nc // 6:] = np.nan # contourf will convert these to masked Z = np.ma.array(Z) # mask another corner: Z[:nr // 6, :nc // 6] = np.ma.masked # mask a circle in the middle: interior = np.sqrt(X**2 + Y**2) < 0.5 Z[interior] = np.ma.masked # We are using automatic selection of contour levels; # this is usually not such a good idea, because they don't # occur on nice boundaries, but we do it here for purposes # of illustration. fig1, ax2 = plt.subplots(constrained_layout=True) CS = ax2.contourf(X, Y, Z, 10, cmap=plt.cm.bone, origin=origin) # Note that in the following, we explicitly pass in a subset of # the contour levels used for the filled contours. Alternatively, # We could pass in additional levels to provide extra resolution, # or leave out the levels kwarg to use all of the original levels. CS2 = ax2.contour(CS, levels=CS.levels[::2], colors='r', origin=origin) ax2.set_title('Nonsense (3 masked regions)') ax2.set_xlabel('word length anomaly') ax2.set_ylabel('sentence length anomaly') # Make a colorbar for the ContourSet returned by the contourf call. cbar = fig1.colorbar(CS) cbar.ax.set_ylabel('verbosity coefficient') # Add the contour line levels to the colorbar cbar.add_lines(CS2) fig2, ax2 = plt.subplots(constrained_layout=True) # Now make a contour plot with the levels specified, # and with the colormap generated automatically from a list # of colors. levels = [-1.5, -1, -0.5, 0, 0.5, 1] CS3 = ax2.contourf(X, Y, Z, levels, colors=('r', 'g', 'b'), origin=origin, extend='both') # Our data range extends outside the range of levels; make # data below the lowest contour level yellow, and above the # highest level cyan: CS3.cmap.set_under('yellow') CS3.cmap.set_over('cyan') CS4 = ax2.contour(X, Y, Z, levels, colors=('k',), linewidths=(3,), origin=origin) ax2.set_title('Listed colors (3 masked regions)') ax2.clabel(CS4, fmt='%2.1f', colors='w', fontsize=14) # Notice that the colorbar command gets all the information it # needs from the ContourSet object, CS3. fig2.colorbar(CS3) # Illustrate all 4 possible "extend" settings: extends = ["neither", "both", "min", "max"] cmap = plt.cm.get_cmap("winter") cmap.set_under("magenta") cmap.set_over("yellow") # Note: contouring simply excludes masked or nan regions, so # instead of using the "bad" colormap value for them, it draws # nothing at all in them. Therefore the following would have # no effect: # cmap.set_bad("red") fig, axs = plt.subplots(2, 2, constrained_layout=True) for ax, extend in zip(axs.ravel(), extends): cs = ax.contourf(X, Y, Z, levels, cmap=cmap, extend=extend, origin=origin) fig.colorbar(cs, ax=ax, shrink=0.9) ax.set_title("extend = %s" % extend) ax.locator_params(nbins=4) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.contour matplotlib.pyplot.contour matplotlib.axes.Axes.contourf matplotlib.pyplot.contourf matplotlib.axes.Axes.clabel matplotlib.pyplot.clabel matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.colors.Colormap matplotlib.colors.Colormap.set_bad matplotlib.colors.Colormap.set_under matplotlib.colors.Colormap.set_over
20402d998c11c704dc49a4903ebe28e35339136862f41a5f8c666a6aa13a5a80
""" ================ Trigradient Demo ================ Demonstrates computation of gradient with `matplotlib.tri.CubicTriInterpolator`. """ from matplotlib.tri import ( Triangulation, UniformTriRefiner, CubicTriInterpolator) import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np #----------------------------------------------------------------------------- # Electrical potential of a dipole #----------------------------------------------------------------------------- def dipole_potential(x, y): """The electric dipole potential V, at position *x*, *y*.""" r_sq = x**2 + y**2 theta = np.arctan2(y, x) z = np.cos(theta)/r_sq return (np.max(z) - z) / (np.max(z) - np.min(z)) #----------------------------------------------------------------------------- # Creating a Triangulation #----------------------------------------------------------------------------- # First create the x and y coordinates of the points. n_angles = 30 n_radii = 10 min_radius = 0.2 radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi / n_angles x = (radii*np.cos(angles)).flatten() y = (radii*np.sin(angles)).flatten() V = dipole_potential(x, y) # Create the Triangulation; no triangles specified so Delaunay triangulation # created. triang = Triangulation(x, y) # Mask off unwanted triangles. triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < min_radius) #----------------------------------------------------------------------------- # Refine data - interpolates the electrical potential V #----------------------------------------------------------------------------- refiner = UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3) #----------------------------------------------------------------------------- # Computes the electrical field (Ex, Ey) as gradient of electrical potential #----------------------------------------------------------------------------- tci = CubicTriInterpolator(triang, -V) # Gradient requested here at the mesh nodes but could be anywhere else: (Ex, Ey) = tci.gradient(triang.x, triang.y) E_norm = np.sqrt(Ex**2 + Ey**2) #----------------------------------------------------------------------------- # Plot the triangulation, the potential iso-contours and the vector field #----------------------------------------------------------------------------- fig, ax = plt.subplots() ax.set_aspect('equal') # Enforce the margins, and enlarge them to give room for the vectors. ax.use_sticky_edges = False ax.margins(0.07) ax.triplot(triang, color='0.8') levels = np.arange(0., 1., 0.01) cmap = cm.get_cmap(name='hot', lut=None) ax.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap, linewidths=[2.0, 1.0, 1.0, 1.0]) # Plots direction of the electrical vector field ax.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm, units='xy', scale=10., zorder=3, color='blue', width=0.007, headwidth=3., headlength=4.) ax.set_title('Gradient plot: an electrical dipole') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.tricontour matplotlib.pyplot.tricontour matplotlib.axes.Axes.triplot matplotlib.pyplot.triplot matplotlib.tri matplotlib.tri.Triangulation matplotlib.tri.CubicTriInterpolator matplotlib.tri.CubicTriInterpolator.gradient matplotlib.tri.UniformTriRefiner matplotlib.axes.Axes.quiver matplotlib.pyplot.quiver
cf6e150fe84f6070bde973ceb8234491920fe4a651f005385a6d769b6931a2c1
""" ============== BboxImage Demo ============== A :class:`~matplotlib.image.BboxImage` can be used to position an image according to a bounding box. This demo shows how to show an image inside a `text.Text`'s bounding box as well as how to manually create a bounding box for the image. """ import matplotlib.pyplot as plt import numpy as np from matplotlib.image import BboxImage from matplotlib.transforms import Bbox, TransformedBbox fig, (ax1, ax2) = plt.subplots(ncols=2) # ---------------------------- # Create a BboxImage with Text # ---------------------------- txt = ax1.text(0.5, 0.5, "test", size=30, ha="center", color="w") kwargs = dict() bbox_image = BboxImage(txt.get_window_extent, norm=None, origin=None, clip_on=False, **kwargs ) a = np.arange(256).reshape(1, 256)/256. bbox_image.set_data(a) ax1.add_artist(bbox_image) # ------------------------------------ # Create a BboxImage for each colormap # ------------------------------------ a = np.linspace(0, 1, 256).reshape(1, -1) a = np.vstack((a, a)) # List of all colormaps; skip reversed colormaps. maps = sorted(m for m in plt.cm.cmap_d if not m.endswith("_r")) ncol = 2 nrow = len(maps)//ncol + 1 xpad_fraction = 0.3 dx = 1./(ncol + xpad_fraction*(ncol - 1)) ypad_fraction = 0.3 dy = 1./(nrow + ypad_fraction*(nrow - 1)) for i, m in enumerate(maps): ix, iy = divmod(i, nrow) bbox0 = Bbox.from_bounds(ix*dx*(1 + xpad_fraction), 1. - iy*dy*(1 + ypad_fraction) - dy, dx, dy) bbox = TransformedBbox(bbox0, ax2.transAxes) bbox_image = BboxImage(bbox, cmap=plt.get_cmap(m), norm=None, origin=None, **kwargs ) bbox_image.set_data(a) ax2.add_artist(bbox_image) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.image.BboxImage matplotlib.transforms.Bbox matplotlib.transforms.TransformedBbox matplotlib.text.Text
da29b4880e1573714d05a13d0ffe02c7ef986f63df4da470076bf6ca68f3ace5
""" =========================== Creating annotated heatmaps =========================== It is often desirable to show data which depends on two independent variables as a color coded image plot. This is often referred to as a heatmap. If the data is categorical, this would be called a categorical heatmap. Matplotlib's :meth:`imshow <matplotlib.axes.Axes.imshow>` function makes production of such plots particularly easy. The following examples show how to create a heatmap with annotations. We will start with an easy example and expand it to be usable as a universal function. """ ############################################################################## # # A simple categorical heatmap # ---------------------------- # # We may start by defining some data. What we need is a 2D list or array # which defines the data to color code. We then also need two lists or arrays # of categories; of course the number of elements in those lists # need to match the data along the respective axes. # The heatmap itself is an :meth:`imshow <matplotlib.axes.Axes.imshow>` plot # with the labels set to the categories we have. # Note that it is important to set both, the tick locations # (:meth:`set_xticks<matplotlib.axes.Axes.set_xticks>`) as well as the # tick labels (:meth:`set_xticklabels<matplotlib.axes.Axes.set_xticklabels>`), # otherwise they would become out of sync. The locations are just # the ascending integer numbers, while the ticklabels are the labels to show. # Finally we can label the data itself by creating a # :class:`~matplotlib.text.Text` within each cell showing the value of # that cell. import numpy as np import matplotlib import matplotlib.pyplot as plt # sphinx_gallery_thumbnail_number = 2 vegetables = ["cucumber", "tomato", "lettuce", "asparagus", "potato", "wheat", "barley"] farmers = ["Farmer Joe", "Upland Bros.", "Smith Gardening", "Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."] harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0], [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0], [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0], [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0], [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0], [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1], [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]]) fig, ax = plt.subplots() im = ax.imshow(harvest) # We want to show all ticks... ax.set_xticks(np.arange(len(farmers))) ax.set_yticks(np.arange(len(vegetables))) # ... and label them with the respective list entries ax.set_xticklabels(farmers) ax.set_yticklabels(vegetables) # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. for i in range(len(vegetables)): for j in range(len(farmers)): text = ax.text(j, i, harvest[i, j], ha="center", va="center", color="w") ax.set_title("Harvest of local farmers (in tons/year)") fig.tight_layout() plt.show() ############################################################################# # Using the helper function code style # ------------------------------------ # # As discussed in the :ref:`Coding styles <coding_styles>` # one might want to reuse such code to create some kind of heatmap # for different input data and/or on different axes. # We create a function that takes the data and the row and column labels as # input, and allows arguments that are used to customize the plot # # Here, in addition to the above we also want to create a colorbar and # position the labels above of the heatmap instead of below it. # The annotations shall get different colors depending on a threshold # for better contrast against the pixel color. # Finally, we turn the surrounding axes spines off and create # a grid of white lines to separate the cells. def heatmap(data, row_labels, col_labels, ax=None, cbar_kw={}, cbarlabel="", **kwargs): """ Create a heatmap from a numpy array and two lists of labels. Parameters ---------- data A 2D numpy array of shape (N, M). row_labels A list or array of length N with the labels for the rows. col_labels A list or array of length M with the labels for the columns. ax A `matplotlib.axes.Axes` instance to which the heatmap is plotted. If not provided, use current axes or create a new one. Optional. cbar_kw A dictionary with arguments to `matplotlib.Figure.colorbar`. Optional. cbarlabel The label for the colorbar. Optional. **kwargs All other arguments are forwarded to `imshow`. """ if not ax: ax = plt.gca() # Plot the heatmap im = ax.imshow(data, **kwargs) # Create colorbar cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw) cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom") # We want to show all ticks... ax.set_xticks(np.arange(data.shape[1])) ax.set_yticks(np.arange(data.shape[0])) # ... and label them with the respective list entries. ax.set_xticklabels(col_labels) ax.set_yticklabels(row_labels) # Let the horizontal axes labeling appear on top. ax.tick_params(top=True, bottom=False, labeltop=True, labelbottom=False) # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=-30, ha="right", rotation_mode="anchor") # Turn spines off and create white grid. for edge, spine in ax.spines.items(): spine.set_visible(False) ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True) ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True) ax.grid(which="minor", color="w", linestyle='-', linewidth=3) ax.tick_params(which="minor", bottom=False, left=False) return im, cbar def annotate_heatmap(im, data=None, valfmt="{x:.2f}", textcolors=["black", "white"], threshold=None, **textkw): """ A function to annotate a heatmap. Parameters ---------- im The AxesImage to be labeled. data Data used to annotate. If None, the image's data is used. Optional. valfmt The format of the annotations inside the heatmap. This should either use the string format method, e.g. "$ {x:.2f}", or be a `matplotlib.ticker.Formatter`. Optional. textcolors A list or array of two color specifications. The first is used for values below a threshold, the second for those above. Optional. threshold Value in data units according to which the colors from textcolors are applied. If None (the default) uses the middle of the colormap as separation. Optional. **kwargs All other arguments are forwarded to each call to `text` used to create the text labels. """ if not isinstance(data, (list, np.ndarray)): data = im.get_array() # Normalize the threshold to the images color range. if threshold is not None: threshold = im.norm(threshold) else: threshold = im.norm(data.max())/2. # Set default alignment to center, but allow it to be # overwritten by textkw. kw = dict(horizontalalignment="center", verticalalignment="center") kw.update(textkw) # Get the formatter in case a string is supplied if isinstance(valfmt, str): valfmt = matplotlib.ticker.StrMethodFormatter(valfmt) # Loop over the data and create a `Text` for each "pixel". # Change the text's color depending on the data. texts = [] for i in range(data.shape[0]): for j in range(data.shape[1]): kw.update(color=textcolors[int(im.norm(data[i, j]) > threshold)]) text = im.axes.text(j, i, valfmt(data[i, j], None), **kw) texts.append(text) return texts ########################################################################## # The above now allows us to keep the actual plot creation pretty compact. # fig, ax = plt.subplots() im, cbar = heatmap(harvest, vegetables, farmers, ax=ax, cmap="YlGn", cbarlabel="harvest [t/year]") texts = annotate_heatmap(im, valfmt="{x:.1f} t") fig.tight_layout() plt.show() ############################################################################# # Some more complex heatmap examples # ---------------------------------- # # In the following we show the versatility of the previously created # functions by applying it in different cases and using different arguments. # np.random.seed(19680801) fig, ((ax, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(8, 6)) # Replicate the above example with a different font size and colormap. im, _ = heatmap(harvest, vegetables, farmers, ax=ax, cmap="Wistia", cbarlabel="harvest [t/year]") annotate_heatmap(im, valfmt="{x:.1f}", size=7) # Create some new data, give further arguments to imshow (vmin), # use an integer format on the annotations and provide some colors. data = np.random.randint(2, 100, size=(7, 7)) y = ["Book {}".format(i) for i in range(1, 8)] x = ["Store {}".format(i) for i in list("ABCDEFG")] im, _ = heatmap(data, y, x, ax=ax2, vmin=0, cmap="magma_r", cbarlabel="weekly sold copies") annotate_heatmap(im, valfmt="{x:d}", size=7, threshold=20, textcolors=["red", "white"]) # Sometimes even the data itself is categorical. Here we use a # :class:`matplotlib.colors.BoundaryNorm` to get the data into classes # and use this to colorize the plot, but also to obtain the class # labels from an array of classes. data = np.random.randn(6, 6) y = ["Prod. {}".format(i) for i in range(10, 70, 10)] x = ["Cycle {}".format(i) for i in range(1, 7)] qrates = np.array(list("ABCDEFG")) norm = matplotlib.colors.BoundaryNorm(np.linspace(-3.5, 3.5, 8), 7) fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: qrates[::-1][norm(x)]) im, _ = heatmap(data, y, x, ax=ax3, cmap=plt.get_cmap("PiYG", 7), norm=norm, cbar_kw=dict(ticks=np.arange(-3, 4), format=fmt), cbarlabel="Quality Rating") annotate_heatmap(im, valfmt=fmt, size=9, fontweight="bold", threshold=-1, textcolors=["red", "black"]) # We can nicely plot a correlation matrix. Since this is bound by -1 and 1, # we use those as vmin and vmax. We may also remove leading zeros and hide # the diagonal elements (which are all 1) by using a # :class:`matplotlib.ticker.FuncFormatter`. corr_matrix = np.corrcoef(np.random.rand(6, 5)) im, _ = heatmap(corr_matrix, vegetables, vegetables, ax=ax4, cmap="PuOr", vmin=-1, vmax=1, cbarlabel="correlation coeff.") def func(x, pos): return "{:.2f}".format(x).replace("0.", ".").replace("1.00", "") annotate_heatmap(im, valfmt=matplotlib.ticker.FuncFormatter(func), size=7) plt.tight_layout() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The usage of the following functions and methods is shown in this example: matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar
94b32fe158e313afb4daf05a042e72ef6b7fb44afeb253166ee8787f03a8cf9e
""" ============================ Clipping images with patches ============================ Demo of image that's been clipped by a circular patch. """ import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.cbook as cbook with cbook.get_sample_data('grace_hopper.png') as image_file: image = plt.imread(image_file) fig, ax = plt.subplots() im = ax.imshow(image) patch = patches.Circle((260, 200), radius=200, transform=ax.transData) im.set_clip_path(patch) ax.axis('off') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown # in this example: import matplotlib matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow matplotlib.artist.Artist.set_clip_path
c4e6cedea426a5941ff15cfc218eeb3d3f35e2295b1a4ee3e4be304fe2452658
""" ================== Quiver Simple Demo ================== A simple example of a `~.axes.Axes.quiver` plot with a `~.axes.Axes.quiverkey`. For more advanced options refer to :doc:`/gallery/images_contours_and_fields/quiver_demo`. """ import matplotlib.pyplot as plt import numpy as np X = np.arange(-10, 10, 1) Y = np.arange(-10, 10, 1) U, V = np.meshgrid(X, Y) fig, ax = plt.subplots() q = ax.quiver(X, Y, U, V) ax.quiverkey(q, X=0.3, Y=1.1, U=10, label='Quiver key, length = 10', labelpos='E') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown in this example: import matplotlib matplotlib.axes.Axes.quiver matplotlib.pyplot.quiver matplotlib.axes.Axes.quiverkey matplotlib.pyplot.quiverkey
25d44c28dbcaa4f5f3ab090d04c626c0ec3e7c922f077b1ae089ccd5f1d67eb9
''' ========= Barb Demo ========= Demonstration of wind barb plots ''' import matplotlib.pyplot as plt import numpy as np x = np.linspace(-5, 5, 5) X, Y = np.meshgrid(x, x) U, V = 12 * X, 12 * Y data = [(-1.5, .5, -6, -6), (1, -1, -46, 46), (-3, -1, 11, -11), (1, 1.5, 80, 80), (0.5, 0.25, 25, 15), (-1.5, -0.5, -5, 40)] data = np.array(data, dtype=[('x', np.float32), ('y', np.float32), ('u', np.float32), ('v', np.float32)]) fig1, axs1 = plt.subplots(nrows=2, ncols=2) # Default parameters, uniform grid axs1[0, 0].barbs(X, Y, U, V) # Arbitrary set of vectors, make them longer and change the pivot point # (point around which they're rotated) to be the middle axs1[0, 1].barbs( data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle') # Showing colormapping with uniform grid. Fill the circle for an empty barb, # don't round the values, and change some of the size parameters axs1[1, 0].barbs( X, Y, U, V, np.sqrt(U ** 2 + V ** 2), fill_empty=True, rounding=False, sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3)) # Change colors as well as the increments for parts of the barbs axs1[1, 1].barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r', barbcolor=['b', 'g'], flip_barb=True, barb_increments=dict(half=10, full=20, flag=100)) # Masked arrays are also supported masked_u = np.ma.masked_array(data['u']) masked_u[4] = 1000 # Bad value that should not be plotted when masked masked_u[4] = np.ma.masked # Identical plot to panel 2 in the first figure, but with the point at # (0.5, 0.25) missing (masked) fig2, ax2 = plt.subplots() ax2.barbs(data['x'], data['y'], masked_u, data['v'], length=8, pivot='middle') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.barbs matplotlib.pyplot.barbs
35a1ec742d3c94e3b4a3c3b86438b42ab02a5abfad45016d1fb44ddcba7e31b4
""" ============ Barcode Demo ============ This demo shows how to produce a one-dimensional image, or "bar code". """ import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) # the bar x = np.random.rand(500) > 0.7 barprops = dict(aspect='auto', cmap='binary', interpolation='nearest') fig = plt.figure() # a vertical barcode ax1 = fig.add_axes([0.1, 0.1, 0.1, 0.8]) ax1.set_axis_off() ax1.imshow(x.reshape((-1, 1)), **barprops) # a horizontal barcode ax2 = fig.add_axes([0.3, 0.4, 0.6, 0.2]) ax2.set_axis_off() ax2.imshow(x.reshape((1, -1)), **barprops) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.imshow matplotlib.pyplot.imshow
16a029940e24d61251da597ea81fdbacabafa899b45529e70ea4df2ce5258f5d
""" ============================ Contourf and log color scale ============================ Demonstrate use of a log color scale in contourf """ import matplotlib.pyplot as plt import numpy as np from numpy import ma from matplotlib import ticker, cm N = 100 x = np.linspace(-3.0, 3.0, N) y = np.linspace(-2.0, 2.0, N) X, Y = np.meshgrid(x, y) # A low hump with a spike coming out. # Needs to have z/colour axis on a log scale so we see both hump and spike. # linear scale only shows the spike. Z1 = np.exp(-(X)**2 - (Y)**2) Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) z = Z1 + 50 * Z2 # Put in some negative values (lower left corner) to cause trouble with logs: z[:5, :5] = -1 # The following is not strictly essential, but it will eliminate # a warning. Comment it out to see the warning. z = ma.masked_where(z <= 0, z) # Automatic selection of levels works; setting the # log locator tells contourf to use a log scale: fig, ax = plt.subplots() cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.PuBu_r) # Alternatively, you can manually set the levels # and the norm: # lev_exp = np.arange(np.floor(np.log10(z.min())-1), # np.ceil(np.log10(z.max())+1)) # levs = np.power(10, lev_exp) # cs = ax.contourf(X, Y, z, levs, norm=colors.LogNorm()) cbar = fig.colorbar(cs) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: import matplotlib matplotlib.axes.Axes.contourf matplotlib.pyplot.contourf matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.axes.Axes.legend matplotlib.pyplot.legend matplotlib.ticker.LogLocator
92aa4ea5b9ee63ee4b0288814dc3af01a8ac952d3145e56a8966f9916e827ecb
""" =============== Watermark image =============== Using a PNG file as a watermark. """ import numpy as np import matplotlib.cbook as cbook import matplotlib.image as image import matplotlib.pyplot as plt with cbook.get_sample_data('logo2.png') as file: im = image.imread(file) fig, ax = plt.subplots() ax.plot(np.sin(10 * np.linspace(0, 1)), '-o', ms=20, alpha=0.7, mfc='orange') ax.grid() fig.figimage(im, 10, 10, zorder=3, alpha=.5) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.image matplotlib.image.imread matplotlib.pyplot.imread matplotlib.figure.Figure.figimage
a3f5fd852734c2ff4e3f9f70b82be665fd9871099df088b4a2534688eaf75d24
""" ========== Streamplot ========== A stream plot, or streamline plot, is used to display 2D vector fields. This example shows a few features of the :meth:`~.axes.Axes.streamplot` function: * Varying the color along a streamline. * Varying the density of streamlines. * Varying the line width along a streamline. * Controlling the starting points of streamlines. * Streamlines skipping masked regions and NaN values. """ import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec w = 3 Y, X = np.mgrid[-w:w:100j, -w:w:100j] U = -1 - X**2 + Y V = 1 + X - Y**2 speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize=(7, 9)) gs = gridspec.GridSpec(nrows=3, ncols=2, height_ratios=[1, 1, 2]) # Varying density along a streamline ax0 = fig.add_subplot(gs[0, 0]) ax0.streamplot(X, Y, U, V, density=[0.5, 1]) ax0.set_title('Varying Density') # Varying color along a streamline ax1 = fig.add_subplot(gs[0, 1]) strm = ax1.streamplot(X, Y, U, V, color=U, linewidth=2, cmap='autumn') fig.colorbar(strm.lines) ax1.set_title('Varying Color') # Varying line width along a streamline ax2 = fig.add_subplot(gs[1, 0]) lw = 5*speed / speed.max() ax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw) ax2.set_title('Varying Line Width') # Controlling the starting points of the streamlines seed_points = np.array([[-2, -1, 0, 1, 2, -1], [-2, -1, 0, 1, 2, 2]]) ax3 = fig.add_subplot(gs[1, 1]) strm = ax3.streamplot(X, Y, U, V, color=U, linewidth=2, cmap='autumn', start_points=seed_points.T) fig.colorbar(strm.lines) ax3.set_title('Controlling Starting Points') # Displaying the starting points with blue symbols. ax3.plot(seed_points[0], seed_points[1], 'bo') ax3.axis((-w, w, -w, w)) # Create a mask mask = np.zeros(U.shape, dtype=bool) mask[40:60, 40:60] = True U[:20, :20] = np.nan U = np.ma.array(U, mask=mask) ax4 = fig.add_subplot(gs[2:, :]) ax4.streamplot(X, Y, U, V, color='r') ax4.set_title('Streamplot with Masking') ax4.imshow(~mask, extent=(-w, w, -w, w), alpha=0.5, interpolation='nearest', cmap='gray', aspect='auto') ax4.set_aspect('equal') plt.tight_layout() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown in this example: import matplotlib matplotlib.axes.Axes.streamplot matplotlib.pyplot.streamplot matplotlib.gridspec matplotlib.gridspec.GridSpec
ed613deb768e6324e92be63e8851332e93ec18d55a452f6c16cb1413b0f2fe67
""" ========== pcolormesh ========== Shows how to combine Normalization and Colormap instances to draw "levels" in :meth:`~.axes.Axes.pcolor`, :meth:`~.axes.Axes.pcolormesh` and :meth:`~.axes.Axes.imshow` type plots in a similar way to the levels keyword argument to contour/contourf. """ import matplotlib import matplotlib.pyplot as plt from matplotlib.colors import BoundaryNorm from matplotlib.ticker import MaxNLocator import numpy as np # make these smaller to increase the resolution dx, dy = 0.05, 0.05 # generate 2 2d grids for the x & y bounds y, x = np.mgrid[slice(1, 5 + dy, dy), slice(1, 5 + dx, dx)] z = np.sin(x)**10 + np.cos(10 + y*x) * np.cos(x) # x and y are bounds, so z should be the value *inside* those bounds. # Therefore, remove the last value from the z array. z = z[:-1, :-1] levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max()) # pick the desired colormap, sensible levels, and define a normalization # instance which takes data values and translates those into levels. cmap = plt.get_cmap('PiYG') norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) fig, (ax0, ax1) = plt.subplots(nrows=2) im = ax0.pcolormesh(x, y, z, cmap=cmap, norm=norm) fig.colorbar(im, ax=ax0) ax0.set_title('pcolormesh with levels') # contours are *point* based plots, so convert our bound into point # centers cf = ax1.contourf(x[:-1, :-1] + dx/2., y[:-1, :-1] + dy/2., z, levels=levels, cmap=cmap) fig.colorbar(cf, ax=ax1) ax1.set_title('contourf with levels') # adjust spacing between subplots so `ax1` title and `ax0` tick labels # don't overlap fig.tight_layout() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions and methods is shown in this example: matplotlib.axes.Axes.pcolormesh matplotlib.pyplot.pcolormesh matplotlib.axes.Axes.contourf matplotlib.pyplot.contourf matplotlib.figure.Figure.colorbar matplotlib.pyplot.colorbar matplotlib.colors.BoundaryNorm matplotlib.ticker.MaxNLocator
54f2eee4ca3e82c4c4a0eacf3c46c4ab51a98528694cedc439cdf6a23470122e
""" ================ Spectrogram Demo ================ Demo of a spectrogram plot (`~.axes.Axes.specgram`). """ import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) dt = 0.0005 t = np.arange(0.0, 20.0, dt) s1 = np.sin(2 * np.pi * 100 * t) s2 = 2 * np.sin(2 * np.pi * 400 * t) # create a transient "chirp" s2[t <= 10] = s2[12 <= t] = 0 # add some noise into the mix nse = 0.01 * np.random.random(size=len(t)) x = s1 + s2 + nse # the signal NFFT = 1024 # the length of the windowing segments Fs = int(1.0 / dt) # the sampling frequency fig, (ax1, ax2) = plt.subplots(nrows=2) ax1.plot(t, x) Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900) # The `specgram` method returns 4 objects. They are: # - Pxx: the periodogram # - freqs: the frequency vector # - bins: the centers of the time bins # - im: the matplotlib.image.AxesImage instance representing the data in the plot plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods is shown # in this example: import matplotlib matplotlib.axes.Axes.specgram matplotlib.pyplot.specgram
e7204328284d8803792284a40e83a4ff211fe6641fdae0e6396f40fb3a054a3b
""" ================ The Sankey class ================ Demonstrate the Sankey class by producing three basic diagrams. """ import matplotlib.pyplot as plt from matplotlib.sankey import Sankey ############################################################################### # Example 1 -- Mostly defaults # # This demonstrates how to create a simple diagram by implicitly calling the # Sankey.add() method and by appending finish() to the call to the class. Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10], labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth'], orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish() plt.title("The default settings produce a diagram like this.") ############################################################################### # Notice: # # 1. Axes weren't provided when Sankey() was instantiated, so they were # created automatically. # 2. The scale argument wasn't necessary since the data was already # normalized. # 3. By default, the lengths of the paths are justified. ############################################################################### # Example 2 # # This demonstrates: # # 1. Setting one path longer than the others # 2. Placing a label in the middle of the diagram # 3. Using the scale argument to normalize the flows # 4. Implicitly passing keyword arguments to PathPatch() # 5. Changing the angle of the arrow heads # 6. Changing the offset between the tips of the paths and their labels # 7. Formatting the numbers in the path labels and the associated unit # 8. Changing the appearance of the patch and the labels after the figure is # created fig = plt.figure() ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Flow Diagram of a Widget") sankey = Sankey(ax=ax, scale=0.01, offset=0.2, head_angle=180, format='%.0f', unit='%') sankey.add(flows=[25, 0, 60, -10, -20, -5, -15, -10, -40], labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth', 'Hurray!'], orientations=[-1, 1, 0, 1, 1, 1, -1, -1, 0], pathlengths=[0.25, 0.25, 0.25, 0.25, 0.25, 0.6, 0.25, 0.25, 0.25], patchlabel="Widget\nA") # Arguments to matplotlib.patches.PathPatch() diagrams = sankey.finish() diagrams[0].texts[-1].set_color('r') diagrams[0].text.set_fontweight('bold') ############################################################################### # Notice: # # 1. Since the sum of the flows is nonzero, the width of the trunk isn't # uniform. The matplotlib logging system logs this at the DEBUG level. # 2. The second flow doesn't appear because its value is zero. Again, this is # logged at the DEBUG level. ############################################################################### # Example 3 # # This demonstrates: # # 1. Connecting two systems # 2. Turning off the labels of the quantities # 3. Adding a legend fig = plt.figure() ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Two Systems") flows = [0.25, 0.15, 0.60, -0.10, -0.05, -0.25, -0.15, -0.10, -0.35] sankey = Sankey(ax=ax, unit=None) sankey.add(flows=flows, label='one', orientations=[-1, 1, 0, 1, 1, 1, -1, -1, 0]) sankey.add(flows=[-0.25, 0.15, 0.1], label='two', orientations=[-1, -1, -1], prior=0, connect=(0, 0)) diagrams = sankey.finish() diagrams[-1].patch.set_hatch('/') plt.legend() ############################################################################### # Notice that only one connection is specified, but the systems form a # circuit since: (1) the lengths of the paths are justified and (2) the # orientation and ordering of the flows is mirrored. plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.sankey matplotlib.sankey.Sankey matplotlib.sankey.Sankey.add matplotlib.sankey.Sankey.finish
18b4aeb9e36f642d55023156420c75d44b5678c5098d16e0736da064461dd78d
""" =============== Hinton diagrams =============== Hinton diagrams are useful for visualizing the values of a 2D array (e.g. a weight matrix): Positive and negative values are represented by white and black squares, respectively, and the size of each square represents the magnitude of each value. Initial idea from David Warde-Farley on the SciPy Cookbook """ import numpy as np import matplotlib.pyplot as plt def hinton(matrix, max_weight=None, ax=None): """Draw Hinton diagram for visualizing a weight matrix.""" ax = ax if ax is not None else plt.gca() if not max_weight: max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2)) ax.patch.set_facecolor('gray') ax.set_aspect('equal', 'box') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(matrix): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(w) / max_weight) rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) ax.autoscale_view() ax.invert_yaxis() if __name__ == '__main__': # Fixing random state for reproducibility np.random.seed(19680801) hinton(np.random.rand(20, 20) - 0.5) plt.show()
836d230537dd8c5b95c2424277ee9f65a5c3d0e129b1f08e47b1e895d5fb2ed8
""" =========== Hillshading =========== Demonstrates a few common tricks with shaded plots. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LightSource, Normalize def display_colorbar(): """Display a correct numeric colorbar for a shaded plot.""" y, x = np.mgrid[-4:2:200j, -4:2:200j] z = 10 * np.cos(x**2 + y**2) cmap = plt.cm.copper ls = LightSource(315, 45) rgb = ls.shade(z, cmap) fig, ax = plt.subplots() ax.imshow(rgb, interpolation='bilinear') # Use a proxy artist for the colorbar... im = ax.imshow(z, cmap=cmap) im.remove() fig.colorbar(im) ax.set_title('Using a colorbar with a shaded plot', size='x-large') def avoid_outliers(): """Use a custom norm to control the displayed z-range of a shaded plot.""" y, x = np.mgrid[-4:2:200j, -4:2:200j] z = 10 * np.cos(x**2 + y**2) # Add some outliers... z[100, 105] = 2000 z[120, 110] = -9000 ls = LightSource(315, 45) fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4.5)) rgb = ls.shade(z, plt.cm.copper) ax1.imshow(rgb, interpolation='bilinear') ax1.set_title('Full range of data') rgb = ls.shade(z, plt.cm.copper, vmin=-10, vmax=10) ax2.imshow(rgb, interpolation='bilinear') ax2.set_title('Manually set range') fig.suptitle('Avoiding Outliers in Shaded Plots', size='x-large') def shade_other_data(): """Demonstrates displaying different variables through shade and color.""" y, x = np.mgrid[-4:2:200j, -4:2:200j] z1 = np.sin(x**2) # Data to hillshade z2 = np.cos(x**2 + y**2) # Data to color norm = Normalize(z2.min(), z2.max()) cmap = plt.cm.RdBu ls = LightSource(315, 45) rgb = ls.shade_rgb(cmap(norm(z2)), z1) fig, ax = plt.subplots() ax.imshow(rgb, interpolation='bilinear') ax.set_title('Shade by one variable, color by another', size='x-large') display_colorbar() avoid_outliers() shade_other_data() plt.show()
c55cf88cf3dabbb745832b452d66f4a0cb4f95385b1bebb1f5822c2edd6db388
""" ======================= Left ventricle bullseye ======================= This example demonstrates how to create the 17 segment model for the left ventricle recommended by the American Heart Association (AHA). """ import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt def bullseye_plot(ax, data, segBold=None, cmap=None, norm=None): """ Bullseye representation for the left ventricle. Parameters ---------- ax : axes data : list of int and float The intensity values for each of the 17 segments segBold : list of int, optional A list with the segments to highlight cmap : ColorMap or None, optional Optional argument to set the desired colormap norm : Normalize or None, optional Optional argument to normalize data into the [0.0, 1.0] range Notes ----- This function create the 17 segment model for the left ventricle according to the American Heart Association (AHA) [1]_ References ---------- .. [1] M. D. Cerqueira, N. J. Weissman, V. Dilsizian, A. K. Jacobs, S. Kaul, W. K. Laskey, D. J. Pennell, J. A. Rumberger, T. Ryan, and M. S. Verani, "Standardized myocardial segmentation and nomenclature for tomographic imaging of the heart", Circulation, vol. 105, no. 4, pp. 539-542, 2002. """ if segBold is None: segBold = [] linewidth = 2 data = np.array(data).ravel() if cmap is None: cmap = plt.cm.viridis if norm is None: norm = mpl.colors.Normalize(vmin=data.min(), vmax=data.max()) theta = np.linspace(0, 2 * np.pi, 768) r = np.linspace(0.2, 1, 4) # Create the bound for the segment 17 for i in range(r.shape[0]): ax.plot(theta, np.repeat(r[i], theta.shape), '-k', lw=linewidth) # Create the bounds for the segments 1-12 for i in range(6): theta_i = np.deg2rad(i * 60) ax.plot([theta_i, theta_i], [r[1], 1], '-k', lw=linewidth) # Create the bounds for the segments 13-16 for i in range(4): theta_i = np.deg2rad(i * 90 - 45) ax.plot([theta_i, theta_i], [r[0], r[1]], '-k', lw=linewidth) # Fill the segments 1-6 r0 = r[2:4] r0 = np.repeat(r0[:, np.newaxis], 128, axis=1).T for i in range(6): # First segment start at 60 degrees theta0 = theta[i * 128:i * 128 + 128] + np.deg2rad(60) theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1) z = np.ones((128, 2)) * data[i] ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm) if i + 1 in segBold: ax.plot(theta0, r0, '-k', lw=linewidth + 2) ax.plot(theta0[0], [r[2], r[3]], '-k', lw=linewidth + 1) ax.plot(theta0[-1], [r[2], r[3]], '-k', lw=linewidth + 1) # Fill the segments 7-12 r0 = r[1:3] r0 = np.repeat(r0[:, np.newaxis], 128, axis=1).T for i in range(6): # First segment start at 60 degrees theta0 = theta[i * 128:i * 128 + 128] + np.deg2rad(60) theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1) z = np.ones((128, 2)) * data[i + 6] ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm) if i + 7 in segBold: ax.plot(theta0, r0, '-k', lw=linewidth + 2) ax.plot(theta0[0], [r[1], r[2]], '-k', lw=linewidth + 1) ax.plot(theta0[-1], [r[1], r[2]], '-k', lw=linewidth + 1) # Fill the segments 13-16 r0 = r[0:2] r0 = np.repeat(r0[:, np.newaxis], 192, axis=1).T for i in range(4): # First segment start at 45 degrees theta0 = theta[i * 192:i * 192 + 192] + np.deg2rad(45) theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1) z = np.ones((192, 2)) * data[i + 12] ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm) if i + 13 in segBold: ax.plot(theta0, r0, '-k', lw=linewidth + 2) ax.plot(theta0[0], [r[0], r[1]], '-k', lw=linewidth + 1) ax.plot(theta0[-1], [r[0], r[1]], '-k', lw=linewidth + 1) # Fill the segments 17 if data.size == 17: r0 = np.array([0, r[0]]) r0 = np.repeat(r0[:, np.newaxis], theta.size, axis=1).T theta0 = np.repeat(theta[:, np.newaxis], 2, axis=1) z = np.ones((theta.size, 2)) * data[16] ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm) if 17 in segBold: ax.plot(theta0, r0, '-k', lw=linewidth + 2) ax.set_ylim([0, 1]) ax.set_yticklabels([]) ax.set_xticklabels([]) # Create the fake data data = np.array(range(17)) + 1 # Make a figure and axes with dimensions as desired. fig, ax = plt.subplots(figsize=(12, 8), nrows=1, ncols=3, subplot_kw=dict(projection='polar')) fig.canvas.set_window_title('Left Ventricle Bulls Eyes (AHA)') # Create the axis for the colorbars axl = fig.add_axes([0.14, 0.15, 0.2, 0.05]) axl2 = fig.add_axes([0.41, 0.15, 0.2, 0.05]) axl3 = fig.add_axes([0.69, 0.15, 0.2, 0.05]) # Set the colormap and norm to correspond to the data for which # the colorbar will be used. cmap = mpl.cm.viridis norm = mpl.colors.Normalize(vmin=1, vmax=17) # ColorbarBase derives from ScalarMappable and puts a colorbar # in a specified axes, so it has everything needed for a # standalone colorbar. There are many more kwargs, but the # following gives a basic continuous colorbar with ticks # and labels. cb1 = mpl.colorbar.ColorbarBase(axl, cmap=cmap, norm=norm, orientation='horizontal') cb1.set_label('Some Units') # Set the colormap and norm to correspond to the data for which # the colorbar will be used. cmap2 = mpl.cm.cool norm2 = mpl.colors.Normalize(vmin=1, vmax=17) # ColorbarBase derives from ScalarMappable and puts a colorbar # in a specified axes, so it has everything needed for a # standalone colorbar. There are many more kwargs, but the # following gives a basic continuous colorbar with ticks # and labels. cb2 = mpl.colorbar.ColorbarBase(axl2, cmap=cmap2, norm=norm2, orientation='horizontal') cb2.set_label('Some other units') # The second example illustrates the use of a ListedColormap, a # BoundaryNorm, and extended ends to show the "over" and "under" # value colors. cmap3 = mpl.colors.ListedColormap(['r', 'g', 'b', 'c']) cmap3.set_over('0.35') cmap3.set_under('0.75') # If a ListedColormap is used, the length of the bounds array must be # one greater than the length of the color list. The bounds must be # monotonically increasing. bounds = [2, 3, 7, 9, 15] norm3 = mpl.colors.BoundaryNorm(bounds, cmap3.N) cb3 = mpl.colorbar.ColorbarBase(axl3, cmap=cmap3, norm=norm3, # to use 'extend', you must # specify two extra boundaries: boundaries=[0] + bounds + [18], extend='both', ticks=bounds, # optional spacing='proportional', orientation='horizontal') cb3.set_label('Discrete intervals, some other units') # Create the 17 segment model bullseye_plot(ax[0], data, cmap=cmap, norm=norm) ax[0].set_title('Bulls Eye (AHA)') bullseye_plot(ax[1], data, cmap=cmap2, norm=norm2) ax[1].set_title('Bulls Eye (AHA)') bullseye_plot(ax[2], data, segBold=[3, 5, 6, 11, 12, 16], cmap=cmap3, norm=norm3) ax[2].set_title('Segments [3,5,6,11,12,16] in bold') plt.show()
40070e46317ac91bd8eb45acf488a84ad0341613e14b4d4f1821f2b358789556
""" ======================= Topographic hillshading ======================= Demonstrates the visual effect of varying blend mode and vertical exaggeration on "hillshaded" plots. Note that the "overlay" and "soft" blend modes work well for complex surfaces such as this example, while the default "hsv" blend mode works best for smooth surfaces such as many mathematical functions. In most cases, hillshading is used purely for visual purposes, and *dx*/*dy* can be safely ignored. In that case, you can tweak *vert_exag* (vertical exaggeration) by trial and error to give the desired visual effect. However, this example demonstrates how to use the *dx* and *dy* kwargs to ensure that the *vert_exag* parameter is the true vertical exaggeration. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.cbook import get_sample_data from matplotlib.colors import LightSource with np.load(get_sample_data('jacksboro_fault_dem.npz')) as dem: z = dem['elevation'] #-- Optional dx and dy for accurate vertical exaggeration ---------------- # If you need topographically accurate vertical exaggeration, or you don't # want to guess at what *vert_exag* should be, you'll need to specify the # cellsize of the grid (i.e. the *dx* and *dy* parameters). Otherwise, any # *vert_exag* value you specify will be relative to the grid spacing of # your input data (in other words, *dx* and *dy* default to 1.0, and # *vert_exag* is calculated relative to those parameters). Similarly, *dx* # and *dy* are assumed to be in the same units as your input z-values. # Therefore, we'll need to convert the given dx and dy from decimal degrees # to meters. dx, dy = dem['dx'], dem['dy'] dy = 111200 * dy dx = 111200 * dx * np.cos(np.radians(dem['ymin'])) #------------------------------------------------------------------------- # Shade from the northwest, with the sun 45 degrees from horizontal ls = LightSource(azdeg=315, altdeg=45) cmap = plt.cm.gist_earth fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(8, 9)) plt.setp(axes.flat, xticks=[], yticks=[]) # Vary vertical exaggeration and blend mode and plot all combinations for col, ve in zip(axes.T, [0.1, 1, 10]): # Show the hillshade intensity image in the first row col[0].imshow(ls.hillshade(z, vert_exag=ve, dx=dx, dy=dy), cmap='gray') # Place hillshaded plots with different blend modes in the rest of the rows for ax, mode in zip(col[1:], ['hsv', 'overlay', 'soft']): rgb = ls.shade(z, cmap=cmap, blend_mode=mode, vert_exag=ve, dx=dx, dy=dy) ax.imshow(rgb) # Label rows and columns for ax, ve in zip(axes[0], [0.1, 1, 10]): ax.set_title('{0}'.format(ve), size=18) for ax, mode in zip(axes[:, 0], ['Hillshade', 'hsv', 'overlay', 'soft']): ax.set_ylabel(mode, size=18) # Group labels... axes[0, 1].annotate('Vertical Exaggeration', (0.5, 1), xytext=(0, 30), textcoords='offset points', xycoords='axes fraction', ha='center', va='bottom', size=20) axes[2, 0].annotate('Blend Mode', (0, 0.5), xytext=(-30, 0), textcoords='offset points', xycoords='axes fraction', ha='right', va='center', size=20, rotation=90) fig.subplots_adjust(bottom=0.05, right=0.95) plt.show()
806f7865231b086b184671933a3d98c65962371c2a22b9de6919b1b7b515f964
""" ====================================== Long chain of connections using Sankey ====================================== Demonstrate/test the Sankey class by producing a long chain of connections. """ import matplotlib.pyplot as plt from matplotlib.sankey import Sankey links_per_side = 6 def side(sankey, n=1): """Generate a side chain.""" prior = len(sankey.diagrams) for i in range(0, 2*n, 2): sankey.add(flows=[1, -1], orientations=[-1, -1], patchlabel=str(prior + i), prior=prior + i - 1, connect=(1, 0), alpha=0.5) sankey.add(flows=[1, -1], orientations=[1, 1], patchlabel=str(prior + i + 1), prior=prior + i, connect=(1, 0), alpha=0.5) def corner(sankey): """Generate a corner link.""" prior = len(sankey.diagrams) sankey.add(flows=[1, -1], orientations=[0, 1], patchlabel=str(prior), facecolor='k', prior=prior - 1, connect=(1, 0), alpha=0.5) fig = plt.figure() ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Why would you want to do this?\n(But you could.)") sankey = Sankey(ax=ax, unit=None) sankey.add(flows=[1, -1], orientations=[0, 1], patchlabel="0", facecolor='k', rotation=45) side(sankey, n=links_per_side) corner(sankey) side(sankey, n=links_per_side) corner(sankey) side(sankey, n=links_per_side) corner(sankey) side(sankey, n=links_per_side) sankey.finish() # Notice: # 1. The alignment doesn't drift significantly (if at all; with 16007 # subdiagrams there is still closure). # 2. The first diagram is rotated 45 deg, so all other diagrams are rotated # accordingly. plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.sankey matplotlib.sankey.Sankey matplotlib.sankey.Sankey.add matplotlib.sankey.Sankey.finish
916a59311abb3a31e725cd63719bd1279f1a9780139cc44fd2b7f20a840f22d5
""" ================== Anscombe's Quartet ================== """ """ Edward Tufte uses this example from Anscombe to show 4 datasets of x and y that have the same mean, standard deviation, and regression line, but which are qualitatively different. matplotlib fun for a rainy day """ import matplotlib.pyplot as plt import numpy as np x = np.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]) y1 = np.array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]) y2 = np.array([9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74]) y3 = np.array([7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73]) x4 = np.array([8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8]) y4 = np.array([6.58, 5.76, 7.71, 8.84, 8.47, 7.04, 5.25, 12.50, 5.56, 7.91, 6.89]) def fit(x): return 3 + 0.5 * x xfit = np.array([np.min(x), np.max(x)]) plt.subplot(221) plt.plot(x, y1, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.text(3, 12, 'I', fontsize=20) plt.subplot(222) plt.plot(x, y2, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), xticks=(0, 10, 20), xticklabels=[], yticks=(4, 8, 12), yticklabels=[], ) plt.text(3, 12, 'II', fontsize=20) plt.subplot(223) plt.plot(x, y3, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.text(3, 12, 'III', fontsize=20) plt.setp(plt.gca(), yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.subplot(224) xfit = np.array([np.min(x4), np.max(x4)]) plt.plot(x4, y4, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), yticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.text(3, 12, 'IV', fontsize=20) # verify the stats pairs = (x, y1), (x, y2), (x, y3), (x4, y4) for x, y in pairs: print('mean=%1.2f, std=%1.2f, r=%1.2f' % (np.mean(y), np.std(y), np.corrcoef(x, y)[0][1])) plt.show()
f8f66dcc8df46cf16489bfde472d2e708fb335403d1baeb814c609f880dc7491
""" ============ MRI With EEG ============ Displays a set of subplots with an MRI image, its intensity histogram and some EEG traces. """ import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook import matplotlib.cm as cm from matplotlib.collections import LineCollection from matplotlib.ticker import MultipleLocator fig = plt.figure("MRI_with_EEG") # Load the MRI data (256x256 16 bit integers) with cbook.get_sample_data('s1045.ima.gz') as dfile: im = np.frombuffer(dfile.read(), np.uint16).reshape((256, 256)) # Plot the MRI image ax0 = fig.add_subplot(2, 2, 1) ax0.imshow(im, cmap=cm.gray) ax0.axis('off') # Plot the histogram of MRI intensity ax1 = fig.add_subplot(2, 2, 2) im = np.ravel(im) im = im[np.nonzero(im)] # Ignore the background im = im / (2**16 - 1) # Normalize ax1.hist(im, bins=100) ax1.xaxis.set_major_locator(MultipleLocator(0.4)) ax1.minorticks_on() ax1.set_yticks([]) ax1.set_xlabel('Intensity (a.u.)') ax1.set_ylabel('MRI density') # Load the EEG data n_samples, n_rows = 800, 4 with cbook.get_sample_data('eeg.dat') as eegfile: data = np.fromfile(eegfile, dtype=float).reshape((n_samples, n_rows)) t = 10 * np.arange(n_samples) / n_samples # Plot the EEG ticklocs = [] ax2 = fig.add_subplot(2, 1, 2) ax2.set_xlim(0, 10) ax2.set_xticks(np.arange(10)) dmin = data.min() dmax = data.max() dr = (dmax - dmin) * 0.7 # Crowd them a bit. y0 = dmin y1 = (n_rows - 1) * dr + dmax ax2.set_ylim(y0, y1) segs = [] for i in range(n_rows): segs.append(np.column_stack((t, data[:, i]))) ticklocs.append(i * dr) offsets = np.zeros((n_rows, 2), dtype=float) offsets[:, 1] = ticklocs lines = LineCollection(segs, offsets=offsets, transOffset=None) ax2.add_collection(lines) # Set the yticks to use axes coordinates on the y axis ax2.set_yticks(ticklocs) ax2.set_yticklabels(['PG3', 'PG5', 'PG7', 'PG9']) ax2.set_xlabel('Time (s)') plt.tight_layout() plt.show()
a935a91e6ae2421ff53a35bd5d180465edaf67d85f2c1793f3d73b2e6dc98429
""" === MRI === This example illustrates how to read an image (of an MRI) into a NumPy array, and display it in greyscale using `imshow`. """ import matplotlib.pyplot as plt import matplotlib.cbook as cbook import numpy as np # Data are 256x256 16 bit integers. with cbook.get_sample_data('s1045.ima.gz') as dfile: im = np.frombuffer(dfile.read(), np.uint16).reshape((256, 256)) fig, ax = plt.subplots(num="MRI_demo") ax.imshow(im, cmap="gray") ax.axis('off') plt.show()
9bb7ca311f3396be271b4601e504d3c586b8546855e0b224557b8551894fe91c
""" =========================================================== SkewT-logP diagram: using transforms and custom projections =========================================================== This serves as an intensive exercise of Matplotlib's transforms and custom projection API. This example produces a so-called SkewT-logP diagram, which is a common plot in meteorology for displaying vertical profiles of temperature. As far as Matplotlib is concerned, the complexity comes from having X and Y axes that are not orthogonal. This is handled by including a skew component to the basic Axes transforms. Additional complexity comes in handling the fact that the upper and lower X-axes have different data ranges, which necessitates a bunch of custom classes for ticks, spines, and axis to handle this. """ from contextlib import ExitStack from matplotlib.axes import Axes import matplotlib.transforms as transforms import matplotlib.axis as maxis import matplotlib.spines as mspines from matplotlib.projections import register_projection # The sole purpose of this class is to look at the upper, lower, or total # interval as appropriate and see what parts of the tick to draw, if any. class SkewXTick(maxis.XTick): def draw(self, renderer): # When adding the callbacks with `stack.callback`, we fetch the current # visibility state of the artist with `get_visible`; the ExitStack will # restore these states (`set_visible`) at the end of the block (after # the draw). with ExitStack() as stack: for artist in [self.gridline, self.tick1line, self.tick2line, self.label1, self.label2]: stack.callback(artist.set_visible, artist.get_visible()) needs_lower = transforms.interval_contains( self.axes.lower_xlim, self.get_loc()) needs_upper = transforms.interval_contains( self.axes.upper_xlim, self.get_loc()) self.tick1line.set_visible( self.tick1line.get_visible() and needs_lower) self.label1.set_visible( self.label1.get_visible() and needs_lower) self.tick2line.set_visible( self.tick2line.get_visible() and needs_upper) self.label2.set_visible( self.label2.get_visible() and needs_upper) super(SkewXTick, self).draw(renderer) def get_view_interval(self): return self.axes.xaxis.get_view_interval() # This class exists to provide two separate sets of intervals to the tick, # as well as create instances of the custom tick class SkewXAxis(maxis.XAxis): def _get_tick(self, major): return SkewXTick(self.axes, None, '', major=major) def get_view_interval(self): return self.axes.upper_xlim[0], self.axes.lower_xlim[1] # This class exists to calculate the separate data range of the # upper X-axis and draw the spine there. It also provides this range # to the X-axis artist for ticking and gridlines class SkewSpine(mspines.Spine): def _adjust_location(self): pts = self._path.vertices if self.spine_type == 'top': pts[:, 0] = self.axes.upper_xlim else: pts[:, 0] = self.axes.lower_xlim # This class handles registration of the skew-xaxes as a projection as well # as setting up the appropriate transformations. It also overrides standard # spines and axes instances as appropriate. class SkewXAxes(Axes): # The projection must specify a name. This will be used be the # user to select the projection, i.e. ``subplot(111, # projection='skewx')``. name = 'skewx' def _init_axis(self): # Taken from Axes and modified to use our modified X-axis self.xaxis = SkewXAxis(self) self.spines['top'].register_axis(self.xaxis) self.spines['bottom'].register_axis(self.xaxis) self.yaxis = maxis.YAxis(self) self.spines['left'].register_axis(self.yaxis) self.spines['right'].register_axis(self.yaxis) def _gen_axes_spines(self): spines = {'top': SkewSpine.linear_spine(self, 'top'), 'bottom': mspines.Spine.linear_spine(self, 'bottom'), 'left': mspines.Spine.linear_spine(self, 'left'), 'right': mspines.Spine.linear_spine(self, 'right')} return spines def _set_lim_and_transforms(self): """ This is called once when the plot is created to set up all the transforms for the data, text and grids. """ rot = 30 # Get the standard transform setup from the Axes base class super()._set_lim_and_transforms() # Need to put the skew in the middle, after the scale and limits, # but before the transAxes. This way, the skew is done in Axes # coordinates thus performing the transform around the proper origin # We keep the pre-transAxes transform around for other users, like the # spines for finding bounds self.transDataToAxes = ( self.transScale + self.transLimits + transforms.Affine2D().skew_deg(rot, 0) ) # Create the full transform from Data to Pixels self.transData = self.transDataToAxes + self.transAxes # Blended transforms like this need to have the skewing applied using # both axes, in axes coords like before. self._xaxis_transform = ( transforms.blended_transform_factory( self.transScale + self.transLimits, transforms.IdentityTransform()) + transforms.Affine2D().skew_deg(rot, 0) + self.transAxes ) @property def lower_xlim(self): return self.axes.viewLim.intervalx @property def upper_xlim(self): pts = [[0., 1.], [1., 1.]] return self.transDataToAxes.inverted().transform(pts)[:, 0] # Now register the projection with matplotlib so the user can select it. register_projection(SkewXAxes) if __name__ == '__main__': # Now make a simple example using the custom projection. from io import StringIO from matplotlib.ticker import (MultipleLocator, NullFormatter, ScalarFormatter) import matplotlib.pyplot as plt import numpy as np # Some example data. data_txt = ''' 978.0 345 7.8 0.8 971.0 404 7.2 0.2 946.7 610 5.2 -1.8 944.0 634 5.0 -2.0 925.0 798 3.4 -2.6 911.8 914 2.4 -2.7 906.0 966 2.0 -2.7 877.9 1219 0.4 -3.2 850.0 1478 -1.3 -3.7 841.0 1563 -1.9 -3.8 823.0 1736 1.4 -0.7 813.6 1829 4.5 1.2 809.0 1875 6.0 2.2 798.0 1988 7.4 -0.6 791.0 2061 7.6 -1.4 783.9 2134 7.0 -1.7 755.1 2438 4.8 -3.1 727.3 2743 2.5 -4.4 700.5 3048 0.2 -5.8 700.0 3054 0.2 -5.8 698.0 3077 0.0 -6.0 687.0 3204 -0.1 -7.1 648.9 3658 -3.2 -10.9 631.0 3881 -4.7 -12.7 600.7 4267 -6.4 -16.7 592.0 4381 -6.9 -17.9 577.6 4572 -8.1 -19.6 555.3 4877 -10.0 -22.3 536.0 5151 -11.7 -24.7 533.8 5182 -11.9 -25.0 500.0 5680 -15.9 -29.9 472.3 6096 -19.7 -33.4 453.0 6401 -22.4 -36.0 400.0 7310 -30.7 -43.7 399.7 7315 -30.8 -43.8 387.0 7543 -33.1 -46.1 382.7 7620 -33.8 -46.8 342.0 8398 -40.5 -53.5 320.4 8839 -43.7 -56.7 318.0 8890 -44.1 -57.1 310.0 9060 -44.7 -58.7 306.1 9144 -43.9 -57.9 305.0 9169 -43.7 -57.7 300.0 9280 -43.5 -57.5 292.0 9462 -43.7 -58.7 276.0 9838 -47.1 -62.1 264.0 10132 -47.5 -62.5 251.0 10464 -49.7 -64.7 250.0 10490 -49.7 -64.7 247.0 10569 -48.7 -63.7 244.0 10649 -48.9 -63.9 243.3 10668 -48.9 -63.9 220.0 11327 -50.3 -65.3 212.0 11569 -50.5 -65.5 210.0 11631 -49.7 -64.7 200.0 11950 -49.9 -64.9 194.0 12149 -49.9 -64.9 183.0 12529 -51.3 -66.3 164.0 13233 -55.3 -68.3 152.0 13716 -56.5 -69.5 150.0 13800 -57.1 -70.1 136.0 14414 -60.5 -72.5 132.0 14600 -60.1 -72.1 131.4 14630 -60.2 -72.2 128.0 14792 -60.9 -72.9 125.0 14939 -60.1 -72.1 119.0 15240 -62.2 -73.8 112.0 15616 -64.9 -75.9 108.0 15838 -64.1 -75.1 107.8 15850 -64.1 -75.1 105.0 16010 -64.7 -75.7 103.0 16128 -62.9 -73.9 100.0 16310 -62.5 -73.5 ''' # Parse the data sound_data = StringIO(data_txt) p, h, T, Td = np.loadtxt(sound_data, unpack=True) # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(6.5875, 6.2125)) ax = fig.add_subplot(111, projection='skewx') plt.grid(True) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorological plot ax.semilogy(T, p, color='C3') ax.semilogy(Td, p, color='C2') # An example of a slanted line at constant X l = ax.axvline(0, color='C0') # Disables the log-formatting that comes with semilogy ax.yaxis.set_major_formatter(ScalarFormatter()) ax.yaxis.set_minor_formatter(NullFormatter()) ax.set_yticks(np.linspace(100, 1000, 10)) ax.set_ylim(1050, 100) ax.xaxis.set_major_locator(MultipleLocator(10)) ax.set_xlim(-50, 50) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.transforms matplotlib.spines matplotlib.spines.Spine matplotlib.spines.Spine.register_axis matplotlib.projections matplotlib.projections.register_projection
1851e7b8795061617407659a65cb989ea29a28cada1ddf4448661120372d9e19
""" =================== Rankine power cycle =================== Demonstrate the Sankey class with a practical example of a Rankine power cycle. """ import matplotlib.pyplot as plt from matplotlib.sankey import Sankey fig = plt.figure(figsize=(8, 9)) ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Rankine Power Cycle: Example 8.6 from Moran and " "Shapiro\n\x22Fundamentals of Engineering Thermodynamics " "\x22, 6th ed., 2008") Hdot = [260.431, 35.078, 180.794, 221.115, 22.700, 142.361, 10.193, 10.210, 43.670, 44.312, 68.631, 10.758, 10.758, 0.017, 0.642, 232.121, 44.559, 100.613, 132.168] # MW sankey = Sankey(ax=ax, format='%.3G', unit=' MW', gap=0.5, scale=1.0/Hdot[0]) sankey.add(patchlabel='\n\nPump 1', rotation=90, facecolor='#37c959', flows=[Hdot[13], Hdot[6], -Hdot[7]], labels=['Shaft power', '', None], pathlengths=[0.4, 0.883, 0.25], orientations=[1, -1, 0]) sankey.add(patchlabel='\n\nOpen\nheater', facecolor='#37c959', flows=[Hdot[11], Hdot[7], Hdot[4], -Hdot[8]], labels=[None, '', None, None], pathlengths=[0.25, 0.25, 1.93, 0.25], orientations=[1, 0, -1, 0], prior=0, connect=(2, 1)) sankey.add(patchlabel='\n\nPump 2', facecolor='#37c959', flows=[Hdot[14], Hdot[8], -Hdot[9]], labels=['Shaft power', '', None], pathlengths=[0.4, 0.25, 0.25], orientations=[1, 0, 0], prior=1, connect=(3, 1)) sankey.add(patchlabel='Closed\nheater', trunklength=2.914, fc='#37c959', flows=[Hdot[9], Hdot[1], -Hdot[11], -Hdot[10]], pathlengths=[0.25, 1.543, 0.25, 0.25], labels=['', '', None, None], orientations=[0, -1, 1, -1], prior=2, connect=(2, 0)) sankey.add(patchlabel='Trap', facecolor='#37c959', trunklength=5.102, flows=[Hdot[11], -Hdot[12]], labels=['\n', None], pathlengths=[1.0, 1.01], orientations=[1, 1], prior=3, connect=(2, 0)) sankey.add(patchlabel='Steam\ngenerator', facecolor='#ff5555', flows=[Hdot[15], Hdot[10], Hdot[2], -Hdot[3], -Hdot[0]], labels=['Heat rate', '', '', None, None], pathlengths=0.25, orientations=[1, 0, -1, -1, -1], prior=3, connect=(3, 1)) sankey.add(patchlabel='\n\n\nTurbine 1', facecolor='#37c959', flows=[Hdot[0], -Hdot[16], -Hdot[1], -Hdot[2]], labels=['', None, None, None], pathlengths=[0.25, 0.153, 1.543, 0.25], orientations=[0, 1, -1, -1], prior=5, connect=(4, 0)) sankey.add(patchlabel='\n\n\nReheat', facecolor='#37c959', flows=[Hdot[2], -Hdot[2]], labels=[None, None], pathlengths=[0.725, 0.25], orientations=[-1, 0], prior=6, connect=(3, 0)) sankey.add(patchlabel='Turbine 2', trunklength=3.212, facecolor='#37c959', flows=[Hdot[3], Hdot[16], -Hdot[5], -Hdot[4], -Hdot[17]], labels=[None, 'Shaft power', None, '', 'Shaft power'], pathlengths=[0.751, 0.15, 0.25, 1.93, 0.25], orientations=[0, -1, 0, -1, 1], prior=6, connect=(1, 1)) sankey.add(patchlabel='Condenser', facecolor='#58b1fa', trunklength=1.764, flows=[Hdot[5], -Hdot[18], -Hdot[6]], labels=['', 'Heat rate', None], pathlengths=[0.45, 0.25, 0.883], orientations=[-1, 1, 0], prior=8, connect=(2, 0)) diagrams = sankey.finish() for diagram in diagrams: diagram.text.set_fontweight('bold') diagram.text.set_fontsize('10') for text in diagram.texts: text.set_fontsize('10') # Notice that the explicit connections are handled automatically, but the # implicit ones currently are not. The lengths of the paths and the trunks # must be adjusted manually, and that is a bit tricky. plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.sankey matplotlib.sankey.Sankey matplotlib.sankey.Sankey.add matplotlib.sankey.Sankey.finish
3bdbdfb5ed755855445230175edf151b33475c2fe6c747cf70e96c65e93e2c8f
""" ====================================== Radar chart (aka spider or star chart) ====================================== This example creates a radar chart, also known as a spider or star chart [1]_. Although this example allows a frame of either 'circle' or 'polygon', polygon frames don't have proper gridlines (the lines are circles instead of polygons). It's possible to get a polygon grid by setting GRIDLINE_INTERPOLATION_STEPS in matplotlib.axis to the desired number of vertices, but the orientation of the polygon is not aligned with the radial axes. .. [1] http://en.wikipedia.org/wiki/Radar_chart """ import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle, RegularPolygon from matplotlib.path import Path from matplotlib.projections.polar import PolarAxes from matplotlib.projections import register_projection from matplotlib.spines import Spine from matplotlib.transforms import Affine2D def radar_factory(num_vars, frame='circle'): """Create a radar chart with `num_vars` axes. This function creates a RadarAxes projection and registers it. Parameters ---------- num_vars : int Number of variables for radar chart. frame : {'circle' | 'polygon'} Shape of frame surrounding axes. """ # calculate evenly-spaced axis angles theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False) class RadarAxes(PolarAxes): name = 'radar' # use 1 line segment to connect specified points RESOLUTION = 1 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # rotate plot such that the first axis is at the top self.set_theta_zero_location('N') def fill(self, *args, closed=True, **kwargs): """Override fill so that line is closed by default""" return super().fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): """Override plot so that line is closed by default""" lines = super().plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() # FIXME: markers at x[0], y[0] get doubled-up if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(np.degrees(theta), labels) def _gen_axes_patch(self): # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5 # in axes coordinates. if frame == 'circle': return Circle((0.5, 0.5), 0.5) elif frame == 'polygon': return RegularPolygon((0.5, 0.5), num_vars, radius=.5, edgecolor="k") else: raise ValueError("unknown value for 'frame': %s" % frame) def _gen_axes_spines(self): if frame == 'circle': return super()._gen_axes_spines() elif frame == 'polygon': # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'. spine = Spine(axes=self, spine_type='circle', path=Path.unit_regular_polygon(num_vars)) # unit_regular_polygon gives a polygon of radius 1 centered at # (0, 0) but we want a polygon of radius 0.5 centered at (0.5, # 0.5) in axes coordinates. spine.set_transform(Affine2D().scale(.5).translate(.5, .5) + self.transAxes) return {'polar': spine} else: raise ValueError("unknown value for 'frame': %s" % frame) register_projection(RadarAxes) return theta def example_data(): # The following data is from the Denver Aerosol Sources and Health study. # See doi:10.1016/j.atmosenv.2008.12.017 # # The data are pollution source profile estimates for five modeled # pollution sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical # species. The radar charts are experimented with here to see if we can # nicely visualize how the modeled source profiles change across four # scenarios: # 1) No gas-phase species present, just seven particulate counts on # Sulfate # Nitrate # Elemental Carbon (EC) # Organic Carbon fraction 1 (OC) # Organic Carbon fraction 2 (OC2) # Organic Carbon fraction 3 (OC3) # Pyrolized Organic Carbon (OP) # 2)Inclusion of gas-phase specie carbon monoxide (CO) # 3)Inclusion of gas-phase specie ozone (O3). # 4)Inclusion of both gas-phase species is present... data = [ ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 'O3'], ('Basecase', [ [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00], [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00], [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00], [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00], [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]]), ('With CO', [ [0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00], [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00], [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00], [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00], [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]]), ('With O3', [ [0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03], [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00], [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00], [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95], [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]]), ('CO & O3', [ [0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01], [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00], [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00], [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88], [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]]) ] return data if __name__ == '__main__': N = 9 theta = radar_factory(N, frame='polygon') data = example_data() spoke_labels = data.pop(0) fig, axes = plt.subplots(figsize=(9, 9), nrows=2, ncols=2, subplot_kw=dict(projection='radar')) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) colors = ['b', 'r', 'g', 'm', 'y'] # Plot the four cases from the example data on separate axes for ax, (title, case_data) in zip(axes.flatten(), data): ax.set_rgrids([0.2, 0.4, 0.6, 0.8]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(case_data, colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) # add legend relative to top-left plot ax = axes[0, 0] labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5') legend = ax.legend(labels, loc=(0.9, .95), labelspacing=0.1, fontsize='small') fig.text(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios', horizontalalignment='center', color='black', weight='bold', size='large') 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.spines matplotlib.spines.Spine matplotlib.projections matplotlib.projections.polar matplotlib.projections.polar.PolarAxes matplotlib.projections.register_projection
f08683f0a948d7653e1b8c9b128423c194e0e692c9e3e42bf3d22675c463f4ea
""" ================== ggplot style sheet ================== This example demonstrates the "ggplot" style, which adjusts the style to emulate ggplot_ (a popular plotting package for R_). These settings were shamelessly stolen from [1]_ (with permission). .. [1] https://web.archive.org/web/20111215111010/http://www.huyng.com/archives/sane-color-scheme-for-matplotlib/691/ .. _ggplot: https://ggplot2.tidyverse.org/ .. _R: https://www.r-project.org/ """ import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') # Fixing random state for reproducibility np.random.seed(19680801) fig, axes = plt.subplots(ncols=2, nrows=2) ax1, ax2, ax3, ax4 = axes.ravel() # scatter plot (Note: `plt.scatter` doesn't use default colors) x, y = np.random.normal(size=(2, 200)) ax1.plot(x, y, 'o') # sinusoidal lines with colors from default color cycle L = 2*np.pi x = np.linspace(0, L) ncolors = len(plt.rcParams['axes.prop_cycle']) shift = np.linspace(0, L, ncolors, endpoint=False) for s in shift: ax2.plot(x, np.sin(x + s), '-') ax2.margins(0) # bar graphs x = np.arange(5) y1, y2 = np.random.randint(1, 25, size=(2, 5)) width = 0.25 ax3.bar(x, y1, width) ax3.bar(x + width, y2, width, color=list(plt.rcParams['axes.prop_cycle'])[2]['color']) ax3.set_xticks(x + width) ax3.set_xticklabels(['a', 'b', 'c', 'd', 'e']) # circles with colors from default color cycle for i, color in enumerate(plt.rcParams['axes.prop_cycle']): xy = np.random.normal(size=2) ax4.add_patch(plt.Circle(xy, radius=0.3, color=color['color'])) ax4.axis('equal') ax4.margins(0) plt.show()
cd8f43d161408299ae26df7a18020a9f782148546026a6360dae2b408eb556db
""" =========================== Dark background style sheet =========================== This example demonstrates the "dark_background" style, which uses white for elements that are typically black (text, borders, etc). Note that not all plot elements default to colors defined by an rc parameter. """ import numpy as np import matplotlib.pyplot as plt plt.style.use('dark_background') fig, ax = plt.subplots() L = 6 x = np.linspace(0, L) ncolors = len(plt.rcParams['axes.prop_cycle']) shift = np.linspace(0, L, ncolors, endpoint=False) for s in shift: ax.plot(x, np.sin(x + s), 'o-') ax.set_xlabel('x-axis') ax.set_ylabel('y-axis') ax.set_title("'dark_background' style sheet") plt.show()
83afb0896300250e2ed843f54c188553d0cf9a4be140423e7485b834cbdb2ddc
""" ======================================== Bayesian Methods for Hackers style sheet ======================================== This example demonstrates the style used in the Bayesian Methods for Hackers [1]_ online book. .. [1] http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/ """ from numpy.random import beta import matplotlib.pyplot as plt plt.style.use('bmh') def plot_beta_hist(ax, a, b): ax.hist(beta(a, b, size=10000), histtype="stepfilled", bins=25, alpha=0.8, density=True) fig, ax = plt.subplots() plot_beta_hist(ax, 10, 10) plot_beta_hist(ax, 4, 12) plot_beta_hist(ax, 50, 12) plot_beta_hist(ax, 6, 55) ax.set_title("'bmh' style sheet") plt.show()
73a070a53d3d6f73659c742c805d0434a742635f3e8cc929c594a0d5671e4067
""" ====================== Style sheets reference ====================== This script demonstrates the different available style sheets on a common set of example plots: scatter plot, image, bar graph, patches, line plot and histogram, """ import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) def plot_scatter(ax, prng, nb_samples=100): """Scatter plot. """ for mu, sigma, marker in [(-.5, 0.75, 'o'), (0.75, 1., 's')]: x, y = prng.normal(loc=mu, scale=sigma, size=(2, nb_samples)) ax.plot(x, y, ls='none', marker=marker) ax.set_xlabel('X-label') return ax def plot_colored_sinusoidal_lines(ax): """Plot sinusoidal lines with colors following the style color cycle. """ L = 2 * np.pi x = np.linspace(0, L) nb_colors = len(plt.rcParams['axes.prop_cycle']) shift = np.linspace(0, L, nb_colors, endpoint=False) for s in shift: ax.plot(x, np.sin(x + s), '-') ax.set_xlim([x[0], x[-1]]) return ax def plot_bar_graphs(ax, prng, min_value=5, max_value=25, nb_samples=5): """Plot two bar graphs side by side, with letters as x-tick labels. """ x = np.arange(nb_samples) ya, yb = prng.randint(min_value, max_value, size=(2, nb_samples)) width = 0.25 ax.bar(x, ya, width) ax.bar(x + width, yb, width, color='C2') ax.set_xticks(x + width) ax.set_xticklabels(['a', 'b', 'c', 'd', 'e']) return ax def plot_colored_circles(ax, prng, nb_samples=15): """Plot circle patches. NB: draws a fixed amount of samples, rather than using the length of the color cycle, because different styles may have different numbers of colors. """ for sty_dict, j in zip(plt.rcParams['axes.prop_cycle'], range(nb_samples)): ax.add_patch(plt.Circle(prng.normal(scale=3, size=2), radius=1.0, color=sty_dict['color'])) # Force the limits to be the same across the styles (because different # styles may have different numbers of available colors). ax.set_xlim([-4, 8]) ax.set_ylim([-5, 6]) ax.set_aspect('equal', adjustable='box') # to plot circles as circles return ax def plot_image_and_patch(ax, prng, size=(20, 20)): """Plot an image with random values and superimpose a circular patch. """ values = prng.random_sample(size=size) ax.imshow(values, interpolation='none') c = plt.Circle((5, 5), radius=5, label='patch') ax.add_patch(c) # Remove ticks ax.set_xticks([]) ax.set_yticks([]) def plot_histograms(ax, prng, nb_samples=10000): """Plot 4 histograms and a text annotation. """ params = ((10, 10), (4, 12), (50, 12), (6, 55)) for a, b in params: values = prng.beta(a, b, size=nb_samples) ax.hist(values, histtype="stepfilled", bins=30, alpha=0.8, density=True) # Add a small annotation. ax.annotate('Annotation', xy=(0.25, 4.25), xytext=(0.9, 0.9), textcoords=ax.transAxes, va="top", ha="right", bbox=dict(boxstyle="round", alpha=0.2), arrowprops=dict( arrowstyle="->", connectionstyle="angle,angleA=-95,angleB=35,rad=10"), ) return ax def plot_figure(style_label=""): """Setup and plot the demonstration figure with a given style. """ # Use a dedicated RandomState instance to draw the same "random" values # across the different figures. prng = np.random.RandomState(96917002) # Tweak the figure size to be better suited for a row of numerous plots: # double the width and halve the height. NB: use relative changes because # some styles may have a figure size different from the default one. (fig_width, fig_height) = plt.rcParams['figure.figsize'] fig_size = [fig_width * 2, fig_height / 2] fig, axes = plt.subplots(ncols=6, nrows=1, num=style_label, figsize=fig_size, squeeze=True) axes[0].set_ylabel(style_label) plot_scatter(axes[0], prng) plot_image_and_patch(axes[1], prng) plot_bar_graphs(axes[2], prng) plot_colored_circles(axes[3], prng) plot_colored_sinusoidal_lines(axes[4]) plot_histograms(axes[5], prng) fig.tight_layout() return fig if __name__ == "__main__": # Setup a list of all available styles, in alphabetical order but # the `default` and `classic` ones, which will be forced resp. in # first and second position. style_list = ['default', 'classic'] + sorted( style for style in plt.style.available if style != 'classic') # Plot a demonstration figure for every available style sheet. for style_label in style_list: with plt.style.context(style_label): fig = plot_figure(style_label=style_label) plt.show()
22f6f924cd830e5bbe036eecc2acefcf5e2571d405024e678ef07535f493b6a5
""" =========================== FiveThirtyEight style sheet =========================== This shows an example of the "fivethirtyeight" styling, which tries to replicate the styles from FiveThirtyEight.com. """ import matplotlib.pyplot as plt import numpy as np plt.style.use('fivethirtyeight') x = np.linspace(0, 10) # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots() ax.plot(x, np.sin(x) + x + np.random.randn(50)) ax.plot(x, np.sin(x) + 0.5 * x + np.random.randn(50)) ax.plot(x, np.sin(x) + 2 * x + np.random.randn(50)) ax.plot(x, np.sin(x) - 0.5 * x + np.random.randn(50)) ax.plot(x, np.sin(x) - 2 * x + np.random.randn(50)) ax.plot(x, np.sin(x) + np.random.randn(50)) ax.set_title("'fivethirtyeight' style sheet") plt.show()
dbbd1fdae424089837ad119dcb4020ecb01a6b25d7c613d9e07b024c0634193f
""" ========================== Solarized Light stylesheet ========================== This shows an example of "Solarized_Light" styling, which tries to replicate the styles of: - `<http://ethanschoonover.com/solarized>`__ - `<https://github.com/jrnold/ggthemes>`__ - `<http://pygal.org/en/stable/documentation/builtin_styles.html#light-solarized>`__ and work of: - `<https://github.com/tonysyu/mpltools>`__ using all 8 accents of the color palette - starting with blue ToDo: - Create alpha values for bar and stacked charts. .33 or .5 - Apply Layout Rules """ import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10) with plt.style.context('Solarize_Light2'): plt.plot(x, np.sin(x) + x + np.random.randn(50)) plt.plot(x, np.sin(x) + 2 * x + np.random.randn(50)) plt.plot(x, np.sin(x) + 3 * x + np.random.randn(50)) plt.plot(x, np.sin(x) + 4 + np.random.randn(50)) plt.plot(x, np.sin(x) + 5 * x + np.random.randn(50)) plt.plot(x, np.sin(x) + 6 * x + np.random.randn(50)) plt.plot(x, np.sin(x) + 7 * x + np.random.randn(50)) plt.plot(x, np.sin(x) + 8 * x + np.random.randn(50)) # Number of accent colors in the color scheme plt.title('8 Random Lines - Line') plt.xlabel('x label', fontsize=14) plt.ylabel('y label', fontsize=14) plt.show()
88798036ba7e3c46ba253eecf2f8e0685d3fd93e6affa5b719786675ff2ff59f
""" ===================== Grayscale style sheet ===================== This example demonstrates the "grayscale" style sheet, which changes all colors that are defined as rc parameters to grayscale. Note, however, that not all plot elements default to colors defined by an rc parameter. """ import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) def color_cycle_example(ax): L = 6 x = np.linspace(0, L) ncolors = len(plt.rcParams['axes.prop_cycle']) shift = np.linspace(0, L, ncolors, endpoint=False) for s in shift: ax.plot(x, np.sin(x + s), 'o-') def image_and_patch_example(ax): ax.imshow(np.random.random(size=(20, 20)), interpolation='none') c = plt.Circle((5, 5), radius=5, label='patch') ax.add_patch(c) plt.style.use('grayscale') fig, (ax1, ax2) = plt.subplots(ncols=2) fig.suptitle("'grayscale' style sheet") color_cycle_example(ax1) image_and_patch_example(ax2) plt.show()
b7d33228b49d1df552e693124f2f184470872a643eb9d5da3c5c00f7a8cd5279
""" ================ Pyplot Formatstr ================ Use a format string to colorize a `~matplotlib.axes.Axes.plot` and set its markers. """ import matplotlib.pyplot as plt plt.plot([1,2,3,4], [1,4,9,16], 'ro') plt.axis([0, 6, 0, 20]) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.pyplot.plot matplotlib.axes.Axes.plot
3655d91fcea2eeb7112eceb931b06b2384c7682e7229de683ddf88f73219942e
""" ==================== Auto Subplots Adjust ==================== Automatically adjust subplot parameters. This example shows a way to determine a subplot parameter from the extent of the ticklabels using a callback on the :doc:`draw_event</users/event_handling>`. Note that a similar result would be achieved using `~.Figure.tight_layout` or `~.Figure.constrained_layout`; this example shows how one could customize the subplot parameter adjustment. """ import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms fig, ax = plt.subplots() ax.plot(range(10)) ax.set_yticks((2,5,7)) labels = ax.set_yticklabels(('really, really, really', 'long', 'labels')) def on_draw(event): bboxes = [] for label in labels: bbox = label.get_window_extent() # the figure transform goes from relative coords->pixels and we # want the inverse of that bboxi = bbox.inverse_transformed(fig.transFigure) bboxes.append(bboxi) # this is the bbox that bounds all the bboxes, again in relative # figure coords bbox = mtransforms.Bbox.union(bboxes) if fig.subplotpars.left < bbox.width: # we need to move it over fig.subplots_adjust(left=1.1*bbox.width) # pad a little fig.canvas.draw() return False fig.canvas.mpl_connect('draw_event', on_draw) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.artist.Artist.get_window_extent matplotlib.transforms.Bbox matplotlib.transforms.Bbox.inverse_transformed matplotlib.transforms.Bbox.union matplotlib.figure.Figure.subplots_adjust matplotlib.figure.SubplotParams matplotlib.backend_bases.FigureCanvasBase.mpl_connect
65738cbef110ccb17921ee43cc03006ae253ccb15511e786bbccfd3bb447df98
""" ============ Boxplot Demo ============ Example boxplot code """ import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) # fake up some data spread = np.random.rand(50) * 100 center = np.ones(25) * 50 flier_high = np.random.rand(10) * 100 + 100 flier_low = np.random.rand(10) * -100 data = np.concatenate((spread, center, flier_high, flier_low)) ############################################################################### fig1, ax1 = plt.subplots() ax1.set_title('Basic Plot') ax1.boxplot(data) ############################################################################### fig2, ax2 = plt.subplots() ax2.set_title('Notched boxes') ax2.boxplot(data, notch=True) ############################################################################### green_diamond = dict(markerfacecolor='g', marker='D') fig3, ax3 = plt.subplots() ax3.set_title('Changed Outlier Symbols') ax3.boxplot(data, flierprops=green_diamond) ############################################################################### fig4, ax4 = plt.subplots() ax4.set_title('Hide Outlier Points') ax4.boxplot(data, showfliers=False) ############################################################################### red_square = dict(markerfacecolor='r', marker='s') fig5, ax5 = plt.subplots() ax5.set_title('Horizontal Boxes') ax5.boxplot(data, vert=False, flierprops=red_square) ############################################################################### fig6, ax6 = plt.subplots() ax6.set_title('Shorter Whisker Length') ax6.boxplot(data, flierprops=red_square, vert=False, whis=0.75) ############################################################################### # Fake up some more data spread = np.random.rand(50) * 100 center = np.ones(25) * 40 flier_high = np.random.rand(10) * 100 + 100 flier_low = np.random.rand(10) * -100 d2 = np.concatenate((spread, center, flier_high, flier_low)) data.shape = (-1, 1) d2.shape = (-1, 1) ############################################################################### # Making a 2-D array only works if all the columns are the # same length. If they are not, then use a list instead. # This is actually more efficient because boxplot converts # a 2-D array into a list of vectors internally anyway. data = [data, d2, d2[::2,0]] fig7, ax7 = plt.subplots() ax7.set_title('Multiple Samples with Different sizes') ax7.boxplot(data) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.boxplot matplotlib.pyplot.boxplot
d1b70c75b13fa20125a2ed5964124e0ac57c858c6bf0a7f221f5dfa8b95b9b3a
""" ========================= Fig Axes Customize Simple ========================= Customize the background, labels and ticks of a simple plot. """ import matplotlib.pyplot as plt ############################################################################### # ``plt.figure`` creates a ```matplotlib.figure.Figure`` instance fig = plt.figure() rect = fig.patch # a rectangle instance rect.set_facecolor('lightgoldenrodyellow') ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4]) rect = ax1.patch rect.set_facecolor('lightslategray') for label in ax1.xaxis.get_ticklabels(): # label is a Text instance label.set_color('tab:red') label.set_rotation(45) label.set_fontsize(16) for line in ax1.yaxis.get_ticklines(): # line is a Line2D instance line.set_color('tab:green') line.set_markersize(25) line.set_markeredgewidth(3) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axis.Axis.get_ticklabels matplotlib.axis.Axis.get_ticklines matplotlib.text.Text.set_rotation matplotlib.text.Text.set_fontsize matplotlib.text.Text.set_color matplotlib.lines.Line2D matplotlib.lines.Line2D.set_color matplotlib.lines.Line2D.set_markersize matplotlib.lines.Line2D.set_markeredgewidth matplotlib.patches.Patch.set_facecolor
0382e5895b88a6df4c5f12b642c8d73a4a985bbc0993a88f1b5b5bc3969b42ed
""" =========== Pyplot Text =========== """ import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 50, density=True, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.text(60, .025, r'$\mu=100,\ \sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.pyplot.hist matplotlib.pyplot.xlabel matplotlib.pyplot.ylabel matplotlib.pyplot.text matplotlib.pyplot.grid matplotlib.pyplot.show
15e03afd73484d4de90ae4892449b5f297b51b8d5dd63f44d08fe3553ed2d24f
""" ============ Fill Between ============ Fill the area between two curves. """ import matplotlib.pyplot as plt import numpy as np x = np.arange(-5, 5, 0.01) y1 = -5*x*x + x + 10 y2 = 5*x*x + x fig, ax = plt.subplots() ax.plot(x, y1, x, y2, color='black') ax.fill_between(x, y1, y2, where=y2 >y1, facecolor='yellow', alpha=0.5) ax.fill_between(x, y1, y2, where=y2 <=y1, facecolor='red', alpha=0.5) ax.set_title('Fill Between') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.fill_between
d3c7a845922ba4dcb73fa61e8f9738ca84d3de0c032eb14d27afb82944ef561f
""" ================== Simple axes labels ================== Label the axes of a plot. """ import numpy as np import matplotlib.pyplot as plt fig = plt.figure() fig.subplots_adjust(top=0.8) ax1 = fig.add_subplot(211) ax1.set_ylabel('volts') ax1.set_title('a sine wave') t = np.arange(0.0, 1.0, 0.01) s = np.sin(2 * np.pi * t) line, = ax1.plot(t, s, lw=2) # Fixing random state for reproducibility np.random.seed(19680801) ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3]) n, bins, patches = ax2.hist(np.random.randn(1000), 50) ax2.set_xlabel('time (s)') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.set_xlabel matplotlib.axes.Axes.set_ylabel matplotlib.axes.Axes.set_title matplotlib.axes.Axes.plot matplotlib.axes.Axes.hist matplotlib.figure.Figure.add_axes
f560b4f1f1a30c00b58eb8ee7a70b8d09f60ce1aa83b670c86994e1f95ddb10c
""" ================ Annotation Polar ================ This example shows how to create an annotation on a polar graph. For a complete overview of the annotation capabilities, also see the :doc:`annotation tutorial</tutorials/text/annotations>`. """ import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, polar=True) r = np.arange(0,1,0.001) theta = 2 * 2*np.pi * r line, = ax.plot(theta, r, color='#ee8d18', lw=3) ind = 800 thisr, thistheta = r[ind], theta[ind] ax.plot([thistheta], [thisr], 'o') ax.annotate('a polar annotation', xy=(thistheta, thisr), # theta, radius xytext=(0.05, 0.05), # fraction, fraction textcoords='figure fraction', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='left', verticalalignment='bottom', ) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.projections.polar matplotlib.axes.Axes.annotate matplotlib.pyplot.annotate
a42c8fc4361ce9cabd243ecd07ffb2f5445f6d32a279f3257f155c8115a2c15d
""" =========== Text Layout =========== Create text with different alignment and rotation. """ 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() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.text matplotlib.pyplot.text
60a697d2879d05f0bfafbf3465d341a47e1e5b28e4b742b6777749e42a844193
""" ===================== Whats New 1 Subplot3d ===================== Create two three-dimensional plots in the same figure. """ from matplotlib import cm #from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(1, 2, 1, projection='3d') X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis, linewidth=0, antialiased=False) ax.set_zlim3d(-1.01, 1.01) #ax.zaxis.set_major_locator(LinearLocator(10)) #ax.zaxis.set_major_formatter(FormatStrFormatter('%.03f')) fig.colorbar(surf, shrink=0.5, aspect=5) from mpl_toolkits.mplot3d.axes3d import get_test_data ax = fig.add_subplot(1, 2, 2, projection='3d') X, Y, Z = get_test_data(0.05) ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib import mpl_toolkits matplotlib.figure.Figure.add_subplot mpl_toolkits.mplot3d.axes3d.Axes3D.plot_surface mpl_toolkits.mplot3d.axes3d.Axes3D.plot_wireframe mpl_toolkits.mplot3d.axes3d.Axes3D.set_zlim3d
f338539352d7ac15d7af17ba5cb19374dc4d58026eceb4c207879badf7469547
""" ============= Text Commands ============= Plotting text of many different kinds. """ 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\374r Festk\366rperphysik') 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() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.figure.Figure.suptitle matplotlib.figure.Figure.add_subplot matplotlib.figure.Figure.subplots_adjust matplotlib.axes.Axes.set_title matplotlib.axes.Axes.set_xlabel matplotlib.axes.Axes.set_ylabel matplotlib.axes.Axes.text matplotlib.axes.Axes.annotate
afc5990ae36ce21dad4345cf97386f698e9395e8a3e056a2a0766b5c17e816c3
""" ======================= Adding lines to figures ======================= Adding lines to a figure without any axes. """ import matplotlib.pyplot as plt import matplotlib.lines as lines fig = plt.figure() l1 = lines.Line2D([0, 1], [0, 1], transform=fig.transFigure, figure=fig) l2 = lines.Line2D([0, 1], [1, 0], transform=fig.transFigure, figure=fig) fig.lines.extend([l1, l2]) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.pyplot.figure matplotlib.lines matplotlib.lines.Line2D
a244954bcf76e947b9308706513ccba5c1a152224ba1e4a5518470e371480305
""" ============ Dollar Ticks ============ Use a `~.ticker.FormatStrFormatter` to prepend dollar signs on y axis labels. """ import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots() ax.plot(100*np.random.rand(20)) formatter = ticker.FormatStrFormatter('$%1.2f') ax.yaxis.set_major_formatter(formatter) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_visible(False) tick.label2.set_visible(True) tick.label2.set_color('green') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.ticker matplotlib.ticker.FormatStrFormatter matplotlib.axis.Axis.set_major_formatter matplotlib.axis.Axis.get_major_ticks matplotlib.axis.Tick
896be2c69569cac0bc425ee04b3e885c1f2505f2055d5c874a7abb1f360a514d
""" ================= Annotating a plot ================= This example shows how to annotate a plot with an arrow pointing to provided coordinates. We modify the defaults of the arrow, to "shrink" it. For a complete overview of the annotation capabilities, also see the :doc:`annotation tutorial</tutorials/text/annotations>`. """ import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = ax.plot(t, s, lw=2) ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), ) ax.set_ylim(-2, 2) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.annotate matplotlib.pyplot.annotate
11899d0737a9cb23cca581ea0dc927f6fa31bce4dcd7b36760cc938a189d4dba
""" ============== Align y-labels ============== Two methods are shown here, one using a short call to `.Figure.align_ylabels` and the second a manual way to align the labels. """ import numpy as np import matplotlib.pyplot as plt def make_plot(axs): box = dict(facecolor='yellow', pad=5, alpha=0.2) # Fixing random state for reproducibility np.random.seed(19680801) ax1 = axs[0, 0] ax1.plot(2000*np.random.rand(10)) ax1.set_title('ylabels not aligned') ax1.set_ylabel('misaligned 1', bbox=box) ax1.set_ylim(0, 2000) ax3 = axs[1, 0] ax3.set_ylabel('misaligned 2', bbox=box) ax3.plot(np.random.rand(10)) ax2 = axs[0, 1] ax2.set_title('ylabels aligned') ax2.plot(2000*np.random.rand(10)) ax2.set_ylabel('aligned 1', bbox=box) ax2.set_ylim(0, 2000) ax4 = axs[1, 1] ax4.plot(np.random.rand(10)) ax4.set_ylabel('aligned 2', bbox=box) # Plot 1: fig, axs = plt.subplots(2, 2) fig.subplots_adjust(left=0.2, wspace=0.6) make_plot(axs) # just align the last column of axes: fig.align_ylabels(axs[:, 1]) plt.show() ############################################################################# # # .. seealso:: # `.Figure.align_ylabels` and `.Figure.align_labels` for a direct method # of doing the same thing. # Also :doc:`/gallery/subplots_axes_and_figures/align_labels_demo` # # # Or we can manually align the axis labels between subplots manually using the # `set_label_coords` method of the y-axis object. Note this requires we know # a good offset value which is hardcoded. fig, axs = plt.subplots(2, 2) fig.subplots_adjust(left=0.2, wspace=0.6) make_plot(axs) labelx = -0.3 # axes coords for j in range(2): axs[j, 1].yaxis.set_label_coords(labelx, 0.5) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.figure.Figure.align_ylabels matplotlib.axis.Axis.set_label_coords matplotlib.axes.Axes.plot matplotlib.pyplot.plot matplotlib.axes.Axes.set_title matplotlib.axes.Axes.set_ylabel matplotlib.axes.Axes.set_ylim
c2d1587e808b0f25a3b4f1eeb8e327068d2163705eb9cba6bbec44f12be27896
""" ================== Annotate Transform ================== This example shows how to use different coordinate systems for annotations. For a complete overview of the annotation capabilities, also see the :doc:`annotation tutorial</tutorials/text/annotations>`. """ import numpy as np import matplotlib.pyplot as plt 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() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.transforms.Transform.transform_point matplotlib.axes.Axes.annotate matplotlib.pyplot.annotate
9fed8b7faf1d356f35fd1fbf388aca4b7a89d3a96835c14f8bacadc540ba73de
""" =================== Pyplot Two Subplots =================== Create a figure with two subplots with `pyplot.subplot`. """ 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, 5.0, 0.1) t2 = np.arange(0.0, 5.0, 0.02) plt.figure() plt.subplot(211) plt.plot(t1, f(t1), color='tab:blue', marker='o') plt.plot(t2, f(t2), color='black') plt.subplot(212) plt.plot(t2, np.cos(2*np.pi*t2), color='tab:orange', linestyle='--') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.pyplot.figure matplotlib.pyplot.subplot
c26a952ba6afbaf94f98307cffad783f6f6e36617c1a4cc0c84a12a58dc5d32d
""" ============= Pyplot Simple ============= A most simple plot, where a list of numbers is plotted against their index. """ import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.pyplot.plot matplotlib.pyplot.ylabel matplotlib.pyplot.show
61f1f98fbd6aa81102d1aacccacb514ead78956704dca55356719f022596162d
""" ======================= Whats New 0.98.4 Legend ======================= Create a legend and tweak it with a shadow and a box. """ import matplotlib.pyplot as plt import numpy as np ax = plt.subplot(111) t1 = np.arange(0.0, 1.0, 0.01) for n in [1, 2, 3, 4]: plt.plot(t1, t1**n, label="n=%d"%(n,)) leg = plt.legend(loc='best', ncol=2, mode="expand", shadow=True, fancybox=True) leg.get_frame().set_alpha(0.5) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.legend matplotlib.pyplot.legend matplotlib.legend.Legend matplotlib.legend.Legend.get_frame
178f52c02a4d5589814a44850caf6b9d9dad4e3f5bfed24a59e6c237e91a79ea
""" ============ Pyplot Three ============ Plot three line plots in a single call to `~matplotlib.pyplot.plot`. """ import numpy as np import matplotlib.pyplot as plt # evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2) # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.pyplot.plot matplotlib.axes.Axes.plot
160d2e5211c41c5c849bed2ccaf27d922582c8a80ab4a9db67a9f41756ec71b5
""" ====================== Whats New 0.98.4 Fancy ====================== Create fancy box and arrow styles. """ import matplotlib.patches as mpatch import matplotlib.pyplot as plt figheight = 8 fig = plt.figure(figsize=(9, figheight), dpi=80) fontsize = 0.4 * fig.dpi def make_boxstyles(ax): styles = mpatch.BoxStyle.get_styles() for i, (stylename, styleclass) in enumerate(sorted(styles.items())): ax.text(0.5, (float(len(styles)) - 0.5 - i)/len(styles), stylename, ha="center", size=fontsize, transform=ax.transAxes, bbox=dict(boxstyle=stylename, fc="w", ec="k")) def make_arrowstyles(ax): styles = mpatch.ArrowStyle.get_styles() ax.set_xlim(0, 4) ax.set_ylim(0, figheight) for i, (stylename, styleclass) in enumerate(sorted(styles.items())): y = (float(len(styles)) - 0.25 - i) # /figheight p = mpatch.Circle((3.2, y), 0.2, fc="w") ax.add_patch(p) ax.annotate(stylename, (3.2, y), (2., y), # xycoords="figure fraction", textcoords="figure fraction", ha="right", va="center", size=fontsize, arrowprops=dict(arrowstyle=stylename, patchB=p, shrinkA=5, shrinkB=5, fc="w", ec="k", connectionstyle="arc3,rad=-0.05", ), bbox=dict(boxstyle="square", fc="w")) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) ax1 = fig.add_subplot(121, frameon=False, xticks=[], yticks=[]) make_boxstyles(ax1) ax2 = fig.add_subplot(122, frameon=False, xticks=[], yticks=[]) make_arrowstyles(ax2) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.patches matplotlib.patches.BoxStyle matplotlib.patches.BoxStyle.get_styles matplotlib.patches.ArrowStyle matplotlib.patches.ArrowStyle.get_styles matplotlib.axes.Axes.text matplotlib.axes.Axes.annotate
147131ca07830e755c28fff637f0a8ca0653fc72d2a0e411edf2dfd9cea590f2
""" ======================== Whats New 0.99 Axes Grid ======================== Create RGB composite images. """ import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes def get_demo_image(): # prepare image delta = 0.5 extent = (-3, 4, -4, 3) x = np.arange(-3.0, 4.001, delta) y = np.arange(-4.0, 3.001, 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 return Z, extent def get_rgb(): Z, extent = get_demo_image() Z[Z < 0] = 0. Z = Z / Z.max() R = Z[:13, :13] G = Z[2:, 2:] B = Z[:13, 2:] return R, G, B fig = plt.figure() ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8]) r, g, b = get_rgb() kwargs = dict(origin="lower", interpolation="nearest") ax.imshow_rgb(r, g, b, **kwargs) ax.RGB.set_xlim(0., 9.5) ax.RGB.set_ylim(0.9, 10.6) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import mpl_toolkits mpl_toolkits.axes_grid1.axes_rgb.RGBAxes mpl_toolkits.axes_grid1.axes_rgb.RGBAxes.imshow_rgb
4581c8db42ca7ab532e43e610486484fb1fb85573e3144f6f5ba1195f13203b6
""" =============== Pyplot Mathtext =============== Use mathematical expressions in text labels. For an overview over MathText see :doc:`/tutorials/text/mathtext`. """ 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) plt.plot(t,s) plt.title(r'$\alpha_i > \beta_i$', fontsize=20) plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20) plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$', fontsize=20) plt.xlabel('time (s)') plt.ylabel('volts (mV)') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.pyplot.text matplotlib.axes.Axes.text
575a54882dbc489c7124776106df035628e6491c40c97b93aa74e2402d132882
""" ====================== Whats New 0.99 Mplot3d ====================== Create a 3D surface plot. """ import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) fig = plt.figure() ax = Axes3D(fig) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import mpl_toolkits mpl_toolkits.mplot3d.Axes3D mpl_toolkits.mplot3d.Axes3D.plot_surface
53463bfa0434f0f80f24db2c82acda287f21112bb877e51c0344c412517eb57c
""" ===================== Whats New 0.99 Spines ===================== """ import matplotlib.pyplot as plt import numpy as np def adjust_spines(ax,spines): for loc, spine in ax.spines.items(): if loc in spines: spine.set_position(('outward', 10)) # outward by 10 points else: spine.set_color('none') # don't draw spine # turn off ticks where there is no spine if 'left' in spines: ax.yaxis.set_ticks_position('left') else: # no yaxis ticks ax.yaxis.set_ticks([]) if 'bottom' in spines: ax.xaxis.set_ticks_position('bottom') else: # no xaxis ticks ax.xaxis.set_ticks([]) fig = plt.figure() x = np.linspace(0,2*np.pi,100) y = 2*np.sin(x) ax = fig.add_subplot(2,2,1) ax.plot(x,y) adjust_spines(ax,['left']) ax = fig.add_subplot(2,2,2) ax.plot(x,y) adjust_spines(ax,[]) ax = fig.add_subplot(2,2,3) ax.plot(x,y) adjust_spines(ax,['left','bottom']) ax = fig.add_subplot(2,2,4) ax.plot(x,y) adjust_spines(ax,['bottom']) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axis.Axis.set_ticks matplotlib.axis.XAxis.set_ticks_position matplotlib.axis.YAxis.set_ticks_position matplotlib.spines matplotlib.spines.Spine matplotlib.spines.Spine.set_color matplotlib.spines.Spine.set_position
13fe7b23bba050ac70c4adde8598f5865d39da3514b3fd29d9e8975f635da7d9
r""" ================ Nested GridSpecs ================ This example demonstrates the use of nested `GridSpec`\s. """ import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import numpy as np from itertools import product def squiggle_xy(a, b, c, d): i = np.arange(0.0, 2*np.pi, 0.05) return np.sin(i*a)*np.cos(i*b), np.sin(i*c)*np.cos(i*d) fig = plt.figure(figsize=(8, 8)) # gridspec inside gridspec outer_grid = gridspec.GridSpec(4, 4, wspace=0.0, hspace=0.0) for i in range(16): inner_grid = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0) a = i // 4 + 1 b = i % 4 + 1 for j, (c, d) in enumerate(product(range(1, 4), repeat=2)): ax = fig.add_subplot(inner_grid[j]) ax.plot(*squiggle_xy(a, b, c, d)) ax.set_xticks([]) ax.set_yticks([]) fig.add_subplot(ax) all_axes = fig.get_axes() # show only the outside spines for ax in all_axes: for sp in ax.spines.values(): sp.set_visible(False) if ax.is_first_row(): ax.spines['top'].set_visible(True) if ax.is_last_row(): ax.spines['bottom'].set_visible(True) if ax.is_first_col(): ax.spines['left'].set_visible(True) if ax.is_last_col(): ax.spines['right'].set_visible(True) plt.show()
65f550cfd5bc1668994eef1d331961a18151e073d7715481c8af8f2022f08c13
""" =============== Simple Legend02 =============== """ import matplotlib.pyplot as plt fig, ax = plt.subplots() line1, = ax.plot([1, 2, 3], label="Line 1", linestyle='--') line2, = ax.plot([3, 2, 1], label="Line 2", linewidth=4) # Create a legend for the first line. first_legend = ax.legend(handles=[line1], loc='upper right') # Add the legend manually to the current Axes. ax.add_artist(first_legend) # Create another legend for the second line. ax.legend(handles=[line2], loc='lower right') plt.show()