How to use the cycler.cycler function in cycler

To help you get started, we’ve selected a few cycler examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github materialsproject / pymatgen / pymatgen / util / plotting.py View on Github external
golden_ratio = (math.sqrt(5) - 1) / 2

    if not height:
        height = int(width * golden_ratio)

    if plt is None:
        import matplotlib.pyplot as plt
        import importlib
        mod = importlib.import_module("palettable.colorbrewer.%s" %
                                      color_cycle[0])
        colors = getattr(mod, color_cycle[1]).mpl_colors
        from cycler import cycler

        plt.figure(figsize=(width, height), facecolor="w", dpi=dpi)
        ax = plt.gca()
        ax.set_prop_cycle(cycler('color', colors))
    else:
        fig = plt.gcf()
        fig.set_size_inches(width, height)
    plt.xticks(fontsize=ticksize)
    plt.yticks(fontsize=ticksize)

    ax = plt.gca()
    ax.set_title(ax.get_title(), size=width * 4)

    labelsize = int(width * 3)

    ax.set_xlabel(ax.get_xlabel(), size=labelsize)
    ax.set_ylabel(ax.get_ylabel(), size=labelsize)

    return plt
github switch-model / switch / switch_model / reporting / basic_exports.py View on Github external
"""
        if by_period:
            df = pd.DataFrame(tab[1:],
                columns = tab[0]).set_index(ind).transpose()
            stack = False
            num_col = int(n_data)/10
        else:
            df = pd.DataFrame(tab[1:], columns = tab[0]).set_index(ind)
            stack = True
            num_col = int(n_data)/2
        fig = plt.figure()
        inv_ax = fig.add_subplot(111)
        inv_ax.grid(b=False)
        # You have to play with the color map and the line style list to
        # get enough combinations for your particular plot
        inv_ax.set_prop_cycle(cycler('color',
                        [color_map(i/n_data) for i in range(0, n_data+1)]))
        # To locate the legend: "loc" is the point of the legend for which you
        # will specify coordinates. These coords are specified in
        # bbox_to_anchor (can be only 1 point or couple)
        inv_plot = df.plot(kind='bar', ax=inv_ax,
            stacked=stack).legend(loc='lower left', fontsize=8,
            bbox_to_anchor=(0.,1.015,1.,1.015), ncol=num_col, mode="expand")
        if by_period:
            plt.xticks(rotation=0, fontsize=10)
            fname = summaries_dir+'/'+name+'.pdf'
        else:
            plt.xticks(rotation=90, fontsize=9)
            fname = summaries_dir+'/'+name+'_stacked_by_p.pdf'
        plt.savefig(fname, bbox_extra_artists=(inv_plot,), bbox_inches='tight')
        plt.close()
github pyrocko / pyrocko / src / gui / util.py View on Github external
def beautify_axes(axes):
    try:
        from cycler import cycler
        axes.set_prop_cycle(
            cycler('color', [to01(x) for x in plot.graph_colors]))

    except (ImportError, KeyError):
        axes.set_color_cycle(list(map(to01, plot.graph_colors)))

    xa = axes.get_xaxis()
    ya = axes.get_yaxis()
    for attr in ('labelpad', 'LABELPAD'):
        if hasattr(xa, attr):
            setattr(xa, attr, xa.get_label().get_fontsize())
            setattr(ya, attr, ya.get_label().get_fontsize())
            break
github libAtoms / matscipy / examples / electrochemistry / cell_1d / pnp_plot.py View on Github external
('dashdotted',            (0, (3, 5, 1, 5))),
     ('densely dashdotted',    (0, (3, 1, 1, 1))),

     ('dashdotdotted',         (0, (3, 5, 1, 5, 1, 5))),
     ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
     ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))]

# color maps for potential and concentration plots
cmap_u = plt.get_cmap('Reds')
cmap_c = [plt.get_cmap('Oranges'), plt.get_cmap('Blues')]

# general line style cycler
line_cycler =   cycler( linestyle = [ s for _,s in linestyle_tuple ] )

# potential anc concentration cyclers
u_cycler    =   cycler( color = cmap_u( np.linspace(0.4,0.8,N) ) )
u_cycler    =   len(line_cycler)*u_cycler + len(u_cycler)*line_cycler
c_cyclers   = [ cycler( color =   cmap( np.linspace(0.4,0.8,N) ) ) for cmap in cmap_c ]
c_cyclers   = [ len(line_cycler)*c_cycler + len(c_cycler)*line_cycler for c_cycler in c_cyclers ]

# https://matplotlib.org/3.1.1/tutorials/intermediate/constrainedlayout_guide.html
fig, (ax1,ax2,ax3) = plt.subplots(
    nrows=1, ncols=3, figsize=[24,7], constrained_layout=True)

ax1.set_xlabel('z (nm)')
ax1.set_ylabel('potential (V)')
ax2.set_xlabel('z (nm)')
ax2.set_ylabel('concentration (mM)')
ax3.set_xlabel('z (nm)')
ax3.set_ylabel('concentration (mM)')

# ax1.axvline(x=pnp.lambda_D()*1e9, label='Debye Length', color='grey', linestyle=':')
github bnikolic / oof / oofpy / examples / plottimings.py View on Github external
import math
import imp # for reload
import json
from itertools import cycle
from cycler import cycler

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

import numpy
import pandas

# NB linestyle cycler broken in matplotlib 2.0.2
plt.rc("axes", prop_cycle=(cycler("color", ['r', 'g', 'b', 'y' ] )+
                           cycler("linestyle", ["-","--","-.",":"])))
plt.rc("savefig", dpi=300)
plt.rc("path", simplify=True)
plt.rc("font", family="serif")
plt.rc("mathtext", fontset ="custom")
plt.rc("text", usetex=True)


for x in ["xtick", "ytick"]:
    plt.rc(x+".major", size=6, width=1)
    plt.rc(x+".minor", size=3, width=1)

plt.rc("lines", markeredgewidth= 1)

plt.rc("legend", numpoints=1, frameon= False, handletextpad=   0.3)
github lukelbd / proplot / trash / sciplotlib_special-axes.py View on Github external
zorder=-1, transform=a.transAxes, ha='center', va='top')
        a.titleleft = a.text(0+titlepad/a.width, 1-titlepad/a.height, '',
                zorder=-1, transform=a.transAxes, ha='left', va='top')
        a.titleright = a.text(1-titlepad/a.width, 1-titlepad/a.height, '',
                zorder=-1, transform=a.transAxes, ha='right', va='top')
        # ABC labeling
        a.abcinside = a.text(abcpad/a.width, 1-abcpad/a.height, ascii_uppercase[i], 
                # bbox=dict(facecolor='w', edgecolor=None, alpha=1),
                transform=a.transAxes, ha='left', va='top', visible=False)
        a.abc = a.text(0, 1, ascii_uppercase[i],
                transform=a.title._transform, ha='left', va='baseline', visible=False) # copies the a.title transform
        # Property cycling
        # To print current cycle, use list(next(ax._get_lines.prop_cycler)['color'] for i in range(10))
        colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
        a.set_prop_cycle(cycler('color', [colors[i%10] for i in range(40)])
                + cycler('linestyle', [i for i in ('-','--','--','--') for n in range(10)])
                + cycler('dashes', [i for i in (tuple(), (1,1), (3,2), (6,3)) for n in range(10)]))

    # Method overrides; plotting (e.g. to fix white lines between polygons), and formatting
    for a in ax:
        # Formatting function
        a.format = MethodType(_format, a) # MethodType approach
        # Mapped overrides
        if projection is not None and package=='basemap':
            # Setup basemap
            a.m = mbasemap.Basemap(projection=projection, ax=a, **projection_kw)
            a.m.drawmapboundary() # **settings().line)
                # must be set before-hand, otherwise this wonky set_axes method automatically draws two mapboundary Patch objects
                # when you plot something, one for fill and the other for the edges; then, since the patch object in 
                # _mapboundarydrawn is only the fill-version, calling drawmapboundar() again will replace only ***that one***, 
                # but the original visible edges is still drawn; if you instead call drawmapboundary right away, calling it again will ***replace*** the object
            # First, set up new methods that fix white edges
github ibell / pdsim / PDSim / plot / plots.py View on Github external
def add(self,name="plot"):
        page = Plot(self.nb)
        self.nb.AddPage(page,name)
        page.figure.gca().set_prop_cycle(
            cycler('color', ['r', 'g', 'b', 'y', 'm', 'c']) *
            cycler('linestyle', ['-', '--', '-.'])
            )

        return page.figure
github lukelbd / proplot / proplot / styletools.py View on Github external
if kwargs:
            warnings.warn(f'Ignoring keyword args {kwargs}.')
    elif all(isinstance(arg, cycler.Cycler) for arg in args):
        # Merge cycler objects
        if kwargs:
            warnings.warn(f'Ignoring keyword args {kwargs}.')
        if len(args) == 1:
            return args[0]
        else:
            props = {}
            for arg in args:
                for key,value in arg.by_key():
                    if key not in props:
                        props[key] = []
                    props[key].extend([*value])
            return cycler.cycler(**props)
    else:
        # Construct and register ListedColormap
        if args and isinstance(args[-1], Number):
            args, samples = args[:-1], args[-1] # means we want to sample existing colormaps or cycles
        kwargs.setdefault('fade', 90)
        kwargs.setdefault('listmode', 'listed')
        cmap = Colormap(*args, **kwargs) # the cmap object itself
        if isinstance(cmap, mcolors.ListedColormap):
            N = samples
            colors = cmap.colors[:N] # if samples is None, does nothing
        else:
            samples = _notNone(samples, 10)
            if isinstance(samples, Integral):
                samples = np.linspace(0, 1, samples) # from edge to edge
            elif np.iterable(samples) and all(isinstance(item,Number) for item in samples):
                samples = np.array(samples)
github lukelbd / proplot / proplot / styletools.py View on Github external
mcm.cmap_d[name] = cmap
        # Save the cycle
        if save:
            basename = f'{name}.hex'
            filename = os.path.join(DATA_USER_CYCLES, basename)
            with open(filename, 'w') as f:
                f.write(','.join(mcolors.to_hex(color) for color in cmap.colors))
            print(f'Saved color cycle to "{basename}".')
        # Add to property dict
        nprops = max(nprops, len(colors))
        props['color'] = cmap.colors # save the tupled version!
    # Build cycler, make sure lengths are the same
    for key,value in props.items():
        if len(value) < nprops:
            value[:] = [value[i%len(value)] for i in range(nprops)] # make loop double back
    return cycler.cycler(**props)

cycler

Composable style cycles

BSD-3-Clause
Latest version published 1 year ago

Package Health Score

77 / 100
Full package analysis