def __init__(self, rename=True, invert=False, **params): # todo from_spec constructor method for this kind of logic cmap = params.pop("cmap", None) cmap = pplt.Colormap(cmap) if cmap else cmap params["cmap"] = cmap super().__init__(**params) self._excluded_from_opts += [ "norm", "sclf", ] # perhaps use leading underscore to exclude? if self.cmap is None and self.norm is None and self.field is not None: cmap, norm = CMAP_NORM_DEFAULTS[self.field] elif self.field is None: cmap = pplt.Colormap("viridis") norm = pplt.Norm("linear", 0.0, 1.0) self.norm = norm self._cmap = cmap # unreversed cmap if rename: cmap.name = self.field + "_default" if invert: cmap = cmap.reversed() self.cmap = cmap
def plot_contourf_save(df, fieldName, title, label, folder_path, cmap=pplot.Colormap('CoolWarm'), levels=250, figwidth=20, vmin=0, vmax=0, dpi=600): dfpivot = df.pivot("y", "x", fieldName) X = dfpivot.columns.values Y = dfpivot.index.values Z = dfpivot.values fig, _ = plot_contourf_Impl(X, Y, Z, title, label, cmap=cmap, levels=levels, figwidth=figwidth, vmin=vmin, vmax=vmax) if not os.path.exists(folder_path): os.mkdir(folder_path) plt.savefig(f"{folder_path}/{title}.jpg".replace(" ", "-"), dpi=dpi) plt.close(fig)
def colormap(self): """ The colormap associated with the variable. """ import proplot as plot cmap = plot.Colormap(self._colormap) if self.axis_reverse: cmap = cmap.reversed() return cmap
def plot_contourf_Impl(X, Y, Z, title, label, cmap=pplot.Colormap('CoolWarm'), levels=250, figwidth=20, vmin=0, vmax=0): figsize = figsize_cm(figwidth, X, Y) fig, ax = plt.subplots(figsize=figsize) # ax.axis('scaled') ax.set_xlim(X.min(), X.max()) ax.set_ylim(Y.min(), Y.max()) ax.set_xlabel('X (m)') ax.set_ylabel('Y (m)') ax.set_title(title) formatter = tickformatter() ax.xaxis.set_major_formatter(formatter) ax.yaxis.set_major_formatter(formatter) Xi, Yi = np.meshgrid(X, Y) if vmin == 0: vmin = np.min(Z) if vmax == 0: vmax = np.max(Z) CS = ax.contourf(Xi, Yi, Z, cmap=cmap, levels=levels, vmin=vmin, vmax=vmax) ax_cb = ax.inset_axes([1.04, 0, 0.02, 1]) # cbarticks = np.arange(vmin,vmax,(vmax-vmin)/10) # fig.colorbar(CS,cax=ax_cb,ticks=cbarticks,label=label) # cbar=fig.colorbar(CS,cax=ax_cb,label=label) cb = clippedcolorbar(CS, cax=ax_cb, label=label, extend='neither') fig.tight_layout() return fig, ax
def plot_contourf(df, fieldName, title, label, cmap=pplot.Colormap('CoolWarm'), levels=250, figwidth=20, vmin=0, vmax=0): dfpivot = df.pivot("y", "x", fieldName) X = dfpivot.columns.values Y = dfpivot.index.values Z = dfpivot.values fig, ax = plot_contourf_Impl(X, Y, Z, title, label, cmap=cmap, levels=levels, figwidth=figwidth, vmin=vmin, vmax=vmax) return fig, ax
# %% import proplot as plot import numpy as np state = np.random.RandomState(51423) data = state.rand(30, 30).cumsum(axis=1) # Initialize figure fig, axs = plot.subplots([[1, 1, 2, 2], [0, 3, 3, 0]], axwidth=2, span=0) axs.format(xlabel='x axis', ylabel='y axis', suptitle='Building your own PerceptuallyUniformColormaps') # Colormap from named color # The trailing '_r' makes the colormap go dark-to-light instead of light-to-dark cmap1 = plot.Colormap('prussian blue_r', name='pacific', fade=100, space='hpl') axs[0].format(title='From single named color') axs[0].pcolormesh(data, cmap=cmap1) # Colormap from lists cmap2 = plot.Colormap(('maroon', 'light tan'), name='heatwave') axs[1].format(title='From list of colors') axs[1].pcolormesh(data, cmap=cmap2) # Colormaps from channel value dictionaries cmap3 = plot.Colormap( { 'hue': ['red', 'red-720'], 'saturation': [80, 20], 'luminance': [20, 100] },
"grey": "#808080", "orange": "#FFA500", "brown": "#A52A2A", "maroon": "#800000", "green": "#008000", "olive": "#808000", "aquamarine": "#7FFFD4", "chocolate": "#D2691E", } sequential_color_maps = colornames = list(colorlist.keys()) pro_colormaps = {} for key in colornames: color = colorlist[key] pro_colormaps[key] = pplt.Colormap(color, l=100, name=f"linear_{key}", space="hpl") sys.path.append("/mnt/data/Research/humor") sys.path.append("/mnt/data/Research/humor/humor") os.environ["PYOPENGL_PLATFORM"] = "osmesa" NUM_BETAS = 10 n2t = torch_utils.numpy2torch c2c = torch_utils.copy2cpu root_orient = n2t(np.array([0, 0, 0])[None, ]) def get_body_directions(root_or, pelvis_xyz, length=1, projection=True): B, _ = root_or.shape
axwidth=2, aspect=1) # Monochromatic colormaps axs.format(xlabel='x axis', ylabel='y axis', span=False, suptitle='Building your own PerceptuallyUniformColormaps') data = state.rand(30, 30).cumsum(axis=1) axs[0].format(title='From single color') m = axs[0].contourf(data, cmap='ocean blue', cmap_kw={'name': 'water'}) cmap1 = m.cmap axs[1].format(title='From three colors') cmap2 = plot.Colormap('dark red_r', 'denim_r', 'warm gray_r', fade=90, name='tricolor') axs[1].contourf(data, cmap=cmap2, levels=12) # Colormaps from channel value dictionaries axs[2:4].format(title='From channel values') cmap3 = plot.Colormap( { 'hue': ['red-90', 'red+90'], 'saturation': [50, 70, 30], 'luminance': [20, 100] }, name='Matter', space='hcl') axs[2].pcolormesh(data, cmap=cmap3)
# DataFrame data = state.rand(12, 20) df = pd.DataFrame((data - 0.4).cumsum(axis=0).cumsum(axis=1)[::1, ::-1], index=pd.date_range('2000-01', '2000-12', freq='MS')) df.name = 'temperature (\N{DEGREE SIGN}C)' df.index.name = 'date' df.columns.name = 'variable (units)' # %% import proplot as pplt fig = pplt.figure(refwidth=2.5, share=False, suptitle='Automatic subplot formatting') # Plot DataArray cmap = pplt.Colormap('PuBu', left=0.05) ax = fig.subplot(121, yreverse=True) ax.contourf(da, cmap=cmap, colorbar='t', lw=0.7, ec='k') # Plot DataFrame ax = fig.subplot(122, yreverse=True) ax.contourf(df, cmap='YlOrRd', colorbar='t', lw=0.7, ec='k') ax.format(xtickminor=False, yformatter='%b', ytickminor=False) # %% [raw] raw_mimetype="text/restructuredtext" # .. _ug_apply_cmap: # # Changing the colormap # --------------------- # # It is often useful to create custom colormaps on-the-fly,
data = state.rand(12, 20) df = pd.DataFrame( (data - 0.4).cumsum(axis=0).cumsum(axis=1), index=list('JFMAMJJASOND'), ) df.name = 'temporal data' df.index.name = 'month' df.columns.name = 'variable (units)' # %% import proplot as plot fig, axs = plot.subplots(nrows=2, axwidth=2.5, share=0) axs.format(toplabels=('Automatic subplot formatting',)) # Plot DataArray cmap = plot.Colormap('RdPu', left=0.05) axs[0].contourf(da, cmap=cmap, colorbar='l', linewidth=0.7, color='k') axs[0].format(yreverse=True) # Plot DataFrame axs[1].contourf(df, cmap='YlOrRd', colorbar='r', linewidth=0.7, color='k') axs[1].format(xtickminor=False) # %% [raw] raw_mimetype="text/restructuredtext" # .. _ug_cmap_changer: # # Colormaps and normalizers # ------------------------- # # It is often useful to create ProPlot colormaps on-the-fly, without
import numpy as np import proplot as plot from matplotlib.colors import LinearSegmentedColormap # dbz colors = [ "#CCCCCC", "#00CCFF", "#0066FF", "#0033CC", "#00FF66", "#33CC66", "#009900", "#FFFF66", "#FFCC33", "#FF9900", "#FF6666", "#FF3333", "#CC0000", "#FF00FF", "#CD00CD", "#800080" ] cmap_name = 'dbz' n_bins = np.arange(-5, 80, 5) cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=16) plot.Colormap(cm, save=True, name=cmap_name)
# `~proplot.utils.units` documentation. They include centimeters, # millimeters, pixels, # `em-heights <https://en.wikipedia.org/wiki/Em_(typography)>`__, # `en-heights <https://en.wikipedia.org/wiki/En_(typography)>`__, # and `points <https://en.wikipedia.org/wiki/Point_(typography)>`__. # %% import proplot as plot import numpy as np with plot.rc.context(fontsize='12px'): fig, axs = plot.subplots(ncols=3, width='15cm', height='3in', wspace=('10pt', '20pt'), right='10mm') cmap = plot.Colormap('Mono') cb = fig.colorbar( cmap, loc='b', extend='both', label='colorbar', width='2em', extendsize='3em', shrink=0.8, ) pax = axs[2].panel('r', width='5en') pax.format(xlim=(0, 1)) axs.format( suptitle='Arguments with arbitrary units', xlabel='x axis', ylabel='y axis',
data, levels=ticks, extend='both', cmap='Mako', norm=norm, colorbar='b', colorbar_kw={'ticks': ticks}, ) axs[i].format(title=title) axs.format(suptitle='Linear segmented normalizer demo') # Diverging norm data1 = (state.rand(20, 20) - 0.43).cumsum(axis=0) data2 = (state.rand(20, 20) - 0.57).cumsum(axis=0) fig, axs = plot.subplots(nrows=2, ncols=2, axwidth=2.5, aspect=1.5, order='F') cmap = plot.Colormap('DryWet', cut=0.1) axs.format(suptitle='Diverging normalizer demo') i = 0 for data, mode, fair in zip((data1, data2), ('positive', 'negative'), ('fair', 'unfair')): for fair in ('fair', 'unfair'): norm = plot.Norm('diverging', fair=(fair == 'fair')) ax = axs[i] m = ax.contourf(data, cmap=cmap, norm=norm) ax.colorbar(m, loc='b', locator=1) ax.format(title=f'Skewed {mode} data, {fair!r} scaling') i += 1 # %% [raw] raw_mimetype="text/restructuredtext" # .. _ug_2dstd: #
# %% import proplot as plot import numpy as np state = np.random.RandomState(51423) fig, axs = plot.subplots(nrows=2, axwidth=3.2, share=0) axs.format(xformatter='null', yformatter='null', abc=True, abcloc='ul', abcstyle='A.', suptitle='Getting individual colors from colormaps and cycles') # Drawing from colormap ax = axs[0] name = 'Deep' cmap = plot.Colormap(name) idxs = plot.arange(0, 1, 0.2) state.shuffle(idxs) 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='r', legend_kw={'ncols': 1}) ax.colorbar(cmap, loc='ur', label='colormap', length='12em') ax.format(title='Drawing from the Solar colormap', grid=True) # Drawing from color cycle ax = axs[1]
fig.format(suptitle='Axis scales demo', ytickminor=True) pplt.rc.reset() # %% import proplot as pplt import numpy as np # Create figure x = np.linspace(0, 4 * np.pi, 100) dy = np.linspace(-1, 1, 5) ys = (np.sin(x), np.cos(x)) state = np.random.RandomState(51423) data = state.rand(len(dy) - 1, len(x) - 1) colors = ('coral', 'sky blue') cmap = pplt.Colormap('grays', right=0.8) fig, axs = pplt.subplots(nrows=4, refaspect=(5, 1), figwidth=5.5, sharex=False) # Loop through various cutoff scale options titles = ('Zoom out of left', 'Zoom into left', 'Discrete jump', 'Fast jump') args = ( (np.pi, 3), # speed up (3 * np.pi, 1 / 3), # slow down (np.pi, np.inf, 3 * np.pi), # discrete jump (np.pi, 5, 3 * np.pi) # fast jump ) locators = ( np.pi / 3, np.pi / 3, np.pi * np.append(np.linspace(0, 1, 4), np.linspace(3, 4, 4)), np.pi * np.append(np.linspace(0, 1, 4), np.linspace(3, 4, 4)),
# 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' ) # Display the channels
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') # Drawing from color cycles name = 'Qual1' idxs = np.arange(6) state.shuffle(idxs) ax = fig.subplot(122, title=f'Drawing from color cycle {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:.0f}', legend='r', legend_kw={'ncols': 1}) ax.colorbar(pplt.Colormap(name), loc='r', locator='none')