# to :rcraw:`cycle` or pass the result of `~proplot.constructor.Cycle` # to :rcraw:`axes.prop_cycle` (see the :ref:`configuration guide <ug_config>`). # %% import proplot as pplt import numpy as np # Sample data state = np.random.RandomState(51423) data = (state.rand(12, 6) - 0.45).cumsum(axis=0) kwargs = {'legend': 'b', 'labels': list('abcdef')} # Figure lw = 5 pplt.rc.cycle = '538' fig = pplt.figure(refwidth=1.9, suptitle='Changing the color cycle') # Modify the default color cycle ax = fig.subplot(131, title='Global color cycle') ax.plot(data, lw=lw, **kwargs) # Pass the cycle to a plotting command ax = fig.subplot(132, title='Local color cycle') ax.plot(data, cycle='qual1', lw=lw, **kwargs) # As above but draw each line individually # Note that passing cycle=name to successive plot calls does # not reset the cycle position if the cycle is unchanged ax = fig.subplot(133, title='Multiple plot calls') labels = kwargs['labels'] for i in range(data.shape[1]):
# To change the :ref:`colorspace <ug_perceptual>` used to construct the colormap, # use the `space` keyword. The default colorspace is ``'hsl'``. In the below example, # we use all of these methods to make `~proplot.colors.PerceptualColormap`\ s # in the ``'hsl'`` and ``'hpl'`` colorspaces. # %% # Sample data import proplot as pplt import numpy as np state = np.random.RandomState(51423) data = state.rand(30, 30).cumsum(axis=1) # %% # Colormap from a color # The trailing '_r' makes the colormap go dark-to-light instead of light-to-dark fig = pplt.figure(refwidth=2, span=False) ax = fig.subplot(121, title='From single named color') cmap1 = pplt.Colormap('prussian blue_r', l=100, name='Pacific', space='hpl') m = ax.contourf(data, cmap=cmap1) ax.colorbar(m, loc='b', ticks='none', label=cmap1.name) # Colormap from lists ax = fig.subplot(122, title='From list of colors') cmap2 = pplt.Colormap(('maroon', 'light tan'), name='Heatwave') m = ax.contourf(data, cmap=cmap2) ax.colorbar(m, loc='b', ticks='none', label=cmap2.name) fig.format( xticklabels='none', yticklabels='none', suptitle='Making PerceptualColormaps' )
# # To generate lists of tick locations, we recommend using proplot's # `~proplot.utils.arange` function -- it’s basically an endpoint-inclusive # version of `numpy.arange`, which is usually what you'll want in this context. # %% import proplot as pplt import numpy as np state = np.random.RandomState(51423) pplt.rc.update( metawidth=1, fontsize=10, metacolor='dark blue', suptitlecolor='dark blue', titleloc='upper center', titlecolor='dark blue', titleborder=False, axesfacecolor=pplt.scale_luminance('powderblue', 1.15), ) fig = pplt.figure(share=False, refwidth=5, refaspect=(8, 1)) fig.format(suptitle='Tick locators demo') # Step size for tick locations ax = fig.subplot(711, title='MultipleLocator') ax.format(xlim=(0, 200), xminorlocator=10, xlocator=30) # Specific list of locations ax = fig.subplot(712, title='FixedLocator') ax.format(xlim=(0, 10), xminorlocator=0.1, xlocator=[0, 0.3, 0.8, 1.6, 4.4, 8, 8.8]) # Ticks at numpy.linspace(xmin, xmax, N) ax = fig.subplot(713, title='LinearLocator') ax.format(xlim=(0, 10), xlocator=('linear', 21)) # Logarithmic locator, used automatically for log scale plots
import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeat import cartopy.io.shapereader as shpreader # read .shp shp_data = shpreader.Reader(r'E:/Downloads/PopulationGrid_China2010/Province_9/Province_9.dbf') provinces = cfeat.ShapelyFeature( shp_data.geometries(), ccrs.PlateCarree(), edgecolor='black', facecolor='none', ) fig = pplt.figure(refwidth=4) axs = fig.subplots(ncols=2, proj='merc', proj_kw={'lon_0': 100}) fig.format( toplabels=('GDP Distribution', 'Population Distribution') ) for ax in axs: ax.format( lonlim=(110, 125), latlim=(20, 40), facecolor='none', labels=True, ) ax.add_feature(provinces, linewidth=0.5, zorder=1) fig.save('fig.png',dpi=600)
# you want to create your subplots :ref:`all-at-once <ug_subplot>` with e.g. # `~proplot.ui.subplots` but need different projections for each subplot, you can pass # a list or dictionary to the `proj` keyword (e.g., ``proj=('cartesian', 'pcarree')`` # or ``proj={2: 'pcarree'}`` -- see `~proplot.figure.Figure.subplots` for details). # Geographic axes are represented with the `~proplot.axes.GeoAxes` subclass, which # has its own `~proplot.axes.GeoAxes.format` command. `proplot.axes.GeoAxes.format` # facilitates :ref:`geographic-specific modifications <ug_geoformat>` like meridional # and parallel gridlines and land mass outlines. The syntax is very similar to # `proplot.axes.CartesianAxes.format`. Note that the `proj` keyword and several of # the `~proplot.axes.GeoAxes.format` keywords are inspired by the basemap API. # In the below example, we create and format a very simple geographic plot. # %% # Use an on-the-fly projection import proplot as pplt fig = pplt.figure(refwidth=3) axs = fig.subplots(nrows=2, proj='robin', proj_kw={'lon0': 150}) # proj = pplt.Proj('robin', lon0=180) # axs = pplt.subplots(nrows=2, proj=proj) # equivalent to above axs.format( suptitle='Figure with single projection', land=True, latlines=30, lonlines=60, ) # %% [raw] raw_mimetype="text/restructuredtext" # .. _ug_backends: # # Geographic backends # -------------------
# %% import proplot as pplt import numpy as np # Sample data state = np.random.RandomState(51423) x = y = np.array([-10, -5, 0, 5, 10]) xedges = pplt.edges(x) yedges = pplt.edges(y) data = state.rand(y.size, x.size) # "center" coordinates lim = (np.min(xedges), np.max(xedges)) with pplt.rc.context({'cmap': 'Grays', 'cmap.levels': 21}): # Figure fig = pplt.figure(refwidth=2.3, share=False) axs = fig.subplots(ncols=2, nrows=2) axs.format( xlabel='xlabel', ylabel='ylabel', xlim=lim, ylim=lim, xlocator=5, ylocator=5, suptitle='Standardized input demonstration', toplabels=('Coordinate centers', 'Coordinate edges'), ) # Plot using both centers and edges as coordinates axs[0].pcolormesh(x, y, data) axs[1].pcolormesh(xedges, yedges, data)
# This can be useful if you wish to restrict the view along a "dependent" variable # axis within a large dataset. To disable this feature, pass ``inbounds=False`` to # the plotting command or set :rcraw:`axes.inbounds` to ``False`` (see also # the :rcraw:`cmap.inbounds` setting and the :ref:`user guide <ug_2dstd>`). # %% import proplot as pplt import numpy as np N = 5 state = np.random.RandomState(51423) with pplt.rc.context({'axes.prop_cycle': pplt.Cycle('Grays', N=N, left=0.3)}): # Sample data x = np.linspace(-5, 5, N) y = state.rand(N, 5) fig = pplt.figure(share=False, suptitle='Standardized input demonstration') # Plot by passing both x and y coordinates ax = fig.subplot(121, title='Manual x coordinates') ax.area(x, -1 * y / N, stack=True) ax.bar(x, y, linewidth=0, alpha=1, width=0.8) ax.plot(x, y + 1, linewidth=2) ax.scatter(x, y + 2, marker='s', markersize=5**2) # Plot by passing just y coordinates # Default x coordinates are inferred from DataFrame, # inferred from DataArray, or set to np.arange(0, y.shape[0]) ax = fig.subplot(122, title='Auto x coordinates') ax.area(-1 * y / N, stack=True) ax.bar(y, linewidth=0, alpha=1) ax.plot(y + 1, linewidth=2)
plt.savefig("Darcy_Forchheimer_Fit.png", dpi=600) plt.show() # ProPlot for i, d in enumerate(data): print(i, d) # fit curve popt, _ = scy.curve_fit(objective, d['x'], d['y']) xx = np.linspace(0, 10, 100) yy = [objective(j, popt[0], popt[1], popt[2]) for j in xx] fig = pplt.figure(share=False) ax = fig.subplot(title='Alternate y twin x') ax.plot(d) ax.plot(d) # # ax.set(xlim=(0, 10), ylim=(0, 150)) ax.set(xlabel="U [m/s]", ylabel='$\Delta$P [Pa]') # Put the legend out of the figure pplt.legend() #plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) pplt.tight_layout()
# .. warning:: # # Proplot employs :ref:`automatic axis sharing <ug_share>` by default. This lets # subplots in the same row or column share the same axis limits, scales, ticks, # and labels. This is often convenient, but may be annoying for some users. To # keep this feature turned off, simply :ref:`change the default settings <ug_rc>` # with e.g. ``pplt.rc.update('subplots', share=False, span=False)``. See the # :ref:`axis sharing section <ug_share>` for details. # %% # Simple subplot grid import numpy as np import proplot as pplt state = np.random.RandomState(51423) data = 2 * (state.rand(100, 5) - 0.5).cumsum(axis=0) fig = pplt.figure() ax = fig.subplot(121) ax.plot(data, lw=2) ax = fig.subplot(122) fig.format(suptitle='Simple subplot grid', title='Title', xlabel='x axis', ylabel='y axis') # fig.save('~/example1.png') # save the figure # fig.savefig('~/example1.png') # alternative # %% # Complex grid import numpy as np import proplot as pplt state = np.random.RandomState(51423)
# subplot (note that subsequently indexing the `~proplot.gridspec.GridSpec` will # ignore the slots allocated for panels). This approach means that panels # :ref:`do not affect subplot aspect ratios <ug_autosize>` and # :ref:`do not affect subplot spacing <ug_tight>`, which lets # proplot avoid relying on complicated `"constrained layout" algorithms # <https://matplotlib.org/stable/tutorials/intermediate/constrainedlayout_guide.html>`__ # and tends to improve the appearance of figures with even the # most complex arrangements of subplots and panels. # %% import proplot as pplt # Demonstrate that complex arrangements preserve # spacing, aspect ratios, and axis sharing gs = pplt.GridSpec(nrows=2, ncols=2) fig = pplt.figure(refwidth=1.5, share=False) for ss, side in zip(gs, 'tlbr'): ax = fig.add_subplot(ss) px = ax.panel_axes(side, width='3em') fig.format( xlim=(0, 1), ylim=(0, 1), xlabel='xlabel', ylabel='ylabel', xticks=0.2, yticks=0.2, title='Title', suptitle='Complex arrangement of panels', toplabels=('Column 1', 'Column 2'), abc=True, abcloc='ul',
# Passed to 'errdata' in the 3rd subplot example means = data.mean(axis=0) means.name = data.name # copy name for formatting fadedata = np.percentile(data, (5, 95), axis=0) # light shading shadedata = np.percentile(data, (25, 75), axis=0) # dark shading # %% import proplot as pplt import numpy as np # Loop through "vertical" and "horizontal" versions varray = [[1], [2], [3]] harray = [[1, 1], [2, 3], [2, 3]] for orientation, array in zip(('vertical', 'horizontal'), (varray, harray)): # Figure fig = pplt.figure(refwidth=4, refaspect=1.5, share=False) axs = fig.subplots(array, hratios=(2, 1, 1)) axs.format(abc='A.', suptitle=f'Indicating {orientation} error bounds') # Medians and percentile ranges ax = axs[0] kw = dict( color='light red', edgecolor='k', legend=True, median=True, barpctile=90, boxpctile=True, # median=True, barpctile=(5, 95), boxpctile=(25, 75) # equivalent ) if orientation == 'horizontal':
# that accepts color specifications (e.g., `color`, `edgecolor`, or `facecolor`). # The ``coord`` should be a float between ``0`` and ``1``, denoting the coordinate # within a smooth colormap, while the ``index`` should be the integer index # on the discrete colormap color list. This feature is powered by the # `~proplot.colors.ColorDatabase` class. This is useful if you spot a # nice color in one of the available colormaps or color cycles and want # to use it for some arbitrary plot element. Use the `~proplot.utils.to_rgb` or # `~proplot.utils.to_rgba` functions to retrieve the RGB or RGBA channel values. # %% import proplot as pplt import numpy as np # Initial figure and random state state = np.random.RandomState(51423) fig = pplt.figure(refwidth=2.2, share=False) # Drawing from colormaps name = 'Deep' idxs = pplt.arange(0, 1, 0.2) state.shuffle(idxs) ax = fig.subplot(121, grid=True, title=f'Drawing from colormap {name!r}') for idx in idxs: data = (state.rand(20) - 0.4).cumsum() h = ax.plot(data, lw=5, color=(name, idx), label=f'idx {idx:.1f}', legend='l', legend_kw={'ncols': 1}) ax.colorbar(pplt.Colormap(name), loc='l', locator='none')
# "stealing" space from the parent subplot (note that subsequently indexing # the `~proplot.gridspec.GridSpec` will ignore the slots allocated for # colorbars and legends). This approach means that "outer" colorbars and # legends :ref:`do not affect subplot aspect ratios <ug_autosize>` # and :ref:`do not affect subplot spacing <ug_tight>`, which lets # proplot avoid relying on complicated `"constrained layout" algorithms # <https://matplotlib.org/stable/tutorials/intermediate/constrainedlayout_guide.html>`__ # and tends to improve the appearance of figures with even the most # complex arrangements of subplots, colorbars, and legends. # %% import proplot as pplt import numpy as np state = np.random.RandomState(51423) fig = pplt.figure(share=False, refwidth=2.3) # Colorbars ax = fig.subplot(121, title='Axes colorbars') data = state.rand(10, 10) m = ax.heatmap(data, cmap='dusk') ax.colorbar(m, loc='r') ax.colorbar(m, loc='t') # title is automatically adjusted ax.colorbar(m, loc='ll', label='colorbar label') # inset colorbar demonstration # Legends ax = fig.subplot(122, title='Axes legends', titlepad='0em') data = (state.rand(10, 5) - 0.5).cumsum(axis=0) hs = ax.plot(data, lw=3, cycle='ggplot', labels=list('abcde')) ax.legend(loc='ll',