Esempio n. 1
0
def colormap_figure():
    """ Generate a figure demonstrating the colormap() function.
    """
    fig, ax = plt.subplots(cmsize=(20.0, 4.0))
    fig.subplots_adjust(leftm=1.5, rightm=1.5, topm=0, bottomm=2)
    colors = palettes['muted']
    cmcolors = [
        colors['red'],
        lighter(colors['orange'], 0.85),
        lighter(colors['yellow'], 0.2),
        lighter(colors['lightblue'], 0.8), colors['blue']
    ]
    cmvalues = [0.0, 0.25, 0.5, 0.8, 1.0]
    colormap('RYB', cmcolors, cmvalues)
    plot_colormap(ax, 'RYB', False)
    fig.savefig('colors-colormap.png')
Esempio n. 2
0
def lighter_figure():
    """ Generate figures demonstrating the lighter() function.
    """
    color = palettes['muted']['blue']
    n = 10
    fig, ax = plt.subplots(cmsize=(1 + 2.2 * (n + 1), 3))
    fig.subplots_adjust(leftm=0, rightm=0, topm=0, bottomm=0)
    ax.show_spines('')
    rectx = np.array([0.0, 1.0, 1.0, 0.0, 0.0])
    recty = np.array([0.0, 0.0, 1.0, 1.0, 0.0])
    for k in range(n + 1):
        fac = 1.0 - k / float(n)
        ax.fill(rectx + 1.2 * k, recty, color=lighter(color, fac))
        ax.text(0.5 + 1.2 * k, -0.3, '%.0f%%' % (100 * fac), ha='center')
    ax.set_xlim(-0.1, (n + 1) * 1.2 - 0.1)
    ax.set_ylim(-0.4, 1.02)
    fig.savefig('colors-lighter.png')
Esempio n. 3
0
def lighter_darker_styles(style, n):
    """ Duplicate style with a range of lighter and darker colors.

    Parameters
    ----------
    style: dict
        A dictionary holding plot style parameter like `linewidth` and `color` or `facecolor`.
    n: int
        Number of modified colors to be generated (`n>1`).

    Returns
    -------
    styles: list of dict
        `n` copies of `style` with `color` or `facecolor` starting from a lighter color,
        traversing over the original color to darker colors.
        The central style has the original color if `n` is odd.

    Example
    -------
    Suppose you have a style for blue lines in a plot like
    ```py
    lsBlue = dict(color=colors['blue'], lw=2)
    ```
    Now you need 5 variants of this plot style with lighter and darker colors.
    Just call
    ```py
    lsBlues = lighter_darker_styles(lsBlue, 5)
    ```
    and you can do something like
    ```py
    for k, ls in enumerate(lsBlues):
        ax.plot(x, y+0.5*k, **ls)
    ```
    """
    for ck in ['color', 'facecolor']:
        if ck in style:
            c = style[ck]
            styles = []
            for k in range(n):
                sd = dict(**style)
                sd[ck] = lighter(c, 1 + (k - (n - 1) / 2) / ((n + 1) // 2))
                styles.append(sd)
            return styles
    return [style] * n
Esempio n. 4
0
def lighter_styles(style, n):
    """ Duplicate style with a range of lighter colors.

    Parameters
    ----------
    style: dict
        A dictionary holding plot style parameter like `linewidth` and `color` or `facecolor`.
    n: int
        Number of lighter colors to be generated (`n>1`).

    Returns
    -------
    styles: list of dict
        `n` copies of `style` with increasingly lighter `color` or `facecolor`.
        The first style is the original one.

    Example
    -------
    Suppose you have a style for blue lines in a plot like
    ```py
    lsBlue = dict(color=colors['blue'], lw=2)
    ```
    Now you need 5 variants of this plot style with increasingly lighter colors.
    Just call
    ```py
    lsBlues = lighter_styles(lsBlue, 5)
    ```
    and you can do something like
    ```py
    for k, ls in enumerate(lsBlues):
        ax.plot(x, y+0.5*k, **ls)
    ```
    """
    for ck in ['color', 'facecolor']:
        if ck in style:
            c = style[ck]
            styles = []
            for k in range(n):
                sd = dict(**style)
                sd[ck] = lighter(c, 1.0 - k / n)
                styles.append(sd)
            return styles
    return [style] * n
Esempio n. 5
0
def make_fillstyles(prefix,
                    names,
                    suffixes,
                    colors,
                    edgecolors,
                    edgewidths,
                    fillalphas,
                    namespace=None,
                    **kwargs):
    """ Generate fill styles.

    The generated dictionaries can be passed as key-word arguments
    to `ax.fill_between()` commands.
    For each corresponding name, color, edge color, edge width and alpha
    a dictionary is generated holding these attributes.
    The generated dictionaries are named `prefix + name + suffix`,
    and are additionally added to the `prefix + suffix` dictionary in the given namespace.
    `name` is also added to the `style_names` list in the namespace.
    
    For example
    ```py
    make_fillstyles('fs', 'PSD', ['', 's', 'a'], [#00FF00], 2.0, 0.5, 0.4)
    ```
    generates the dictionaries named `fsPSD`, `fsPSDs`, `fsPSDa` defining a green fill color.
    The first, `fsPSD` gets a black edge color with edge width set to 0.5.
    The second, `fsPSDs` is without edge.
    The third, `fsPSDa` is without edge and has alpha set to 0.4.
    Further, `PSD` is added to `style_names`, and the three dictionaries are added
    to the `fs`, `fss` and `fsa` dictionaries under the key `PSD`.
    Simply throw the dictionaries into a `fill_between()` command:
    ```py
    plt.fill_between(x, y0, y1, **fsPSD)
    ```
    or like this (here for a transparent fill style):
    ```py
    plt.plot(x, y, **fsa['PSD'])
    ```

    Parameters
    ----------
    prefix: string
        Prefix prepended to all fill style names.
    names: string or list of strings
        Names of the line styles.
        If string and a '%' is contained, then formats like '%d' are replaced
        by the index of the line style plus one.
    suffixes: list of strings or None
        Sufffixes appended to all fill style names.  The first is for a
        fill style with edge color, the second for a solid fill style
        without edge, and the third for a transparent fill style without
        edge. If None the corresponding style is not generated.
    colors: matplotlib color or list of matplotlib colors
        Fill colors.
    edgecolors: float or list of floats
        Defines edge colors for the first fill style.
        It is passed as the lightness argument to `lighter()`
        using the face color from `colors`. That is, 0 results in a white edge color,
        1 in an edge with the same color as the face color, and 2 in a black edge color.
    edgewidth: float or list of floats
        Widths for the edge color of the first fill style.
    fillalphas: float or list of floats
        Alpha values for the transparent (third) fill style.
    namespace: dict or None
        Namespace to which the generated fill styles are added.
        If None add fill styles to the __main__ module.
    kwargs: dict
        Key-word arguments with further fill properties, e.g. zorder.
    """
    # prepare dictionaries:
    if namespace is None:
        namespace = __main__
    if not hasattr(namespace, 'style_names'):
        namespace.style_names = []
    for suffix in suffixes:
        if suffix is not None:
            ln = prefix + suffix
            if not hasattr(namespace, ln):
                setattr(namespace, ln, {})
    # number of line styles to be generated:
    n = 1
    for x in (names, colors, edgecolors, edgewidths, fillalphas):
        if isinstance(x, (tuple, list)) and len(x) > n:
            n = len(x)
    # generate styles:
    for k in range(n):
        if isinstance(names, (tuple, list)):
            name = names[k]
        else:
            if '%' in names:
                name = names % (k + 1)
            else:
                name = names
        if name not in namespace.style_names:
            namespace.style_names.append(name)
        for j, suffix in enumerate(suffixes):
            if suffix is not None:
                sn = prefix + name + suffix
                c = colors[k] if isinstance(colors, (tuple, list)) else colors
                ec = edgecolors[k] if isinstance(edgecolors,
                                                 (tuple, list)) else edgecolors
                ew = edgewidths[k] if isinstance(edgewidths,
                                                 (tuple, list)) else edgewidths
                fa = fillalphas[k] if isinstance(fillalphas,
                                                 (tuple, list)) else fillalphas
                filldict = dict(facecolor=c, **kwargs)
                if j == 0:  # fill with edge:
                    filldict.update(
                        dict(edgecolor=lighter(c, ec), linewidth=ew))
                elif j == 1:  # fill without edge:
                    filldict.update(dict(edgecolor='none'))
                elif j == 2:  # fill without edge, with alpha:
                    filldict.update(dict(edgecolor='none', alpha=fa))
                setattr(namespace, sn, filldict)
                getattr(namespace, prefix + suffix)[name] = filldict
Esempio n. 6
0
def make_pointstyles(prefix,
                     names,
                     suffix,
                     colors,
                     dashes='none',
                     lws=0,
                     markers=('o', 1.0),
                     markersizes=5.0,
                     markeredgecolors=0.0,
                     markeredgewidths=1.0,
                     namespace=None,
                     **kwargs):
    """ Generate point styles.

    The generated dictionaries can be passed as key-word arguments to `ax.plot()` commands.
    For each corresponding name, color, line style, line width, marker, marker size,
    marker edge color and marker edge width a dictionary is generated holding these attributes.
    The generated dictionaries are named `prefix + name + suffix`,
    and are additionally added to the `prefix + suffix` dictionary in the given namespace.
    `name` is also added to the `style_names` list in the namespace.
    
    For example
    ```py
    make_pointstyles('ps', 'Female', '', 'red', '-', 1, ('o', 1.0), 8, 0.5, 1, alpha=0.5)
    ```
    generates a dictionary named `psFemale` defining transparent red filled markers
    with a lighter edge, adds `Female` to `style_names`,
    and adds the dictionary to `ps` under the key `Female`.
    Simply throw the dictionary into a `plot()` command:
    ```py
    plt.plot(x, y, **psFemale)
    ```
    this is the same as:
    ```py
    plt.plot(x, y, **ps['Female'])
    ```
    This
    ```py
    make_pointstyles('ps', 'Reds%d', 'c', ['red', 'orange', 'yellow'], 'none', 0, ('o', 1.0), 8, 1, 0)
    ```
    generates 'psReds1',  'psReds2',  'psReds3' for plotting
    filled circels with colors red, orange, and yellow, respectively.

    Parameters
    ----------
    prefix: string
        Prefix prepended to all point style names.
    names: string or list of strings
        Names of the line styles.
        If string and a '%' is contained, then formats like '%d' are replaced
        by the index of the line style plus one.
    suffix: string or list of strings
        Sufffix appended to all point style names.
    colors: matplotlib color or list of matplotlib colors
        For each color in the list a point style is generated.
    dashes: matplotlib linestyle or list of matplotlib linestyles
        Dash styles of the connecting lines. If points are not to be connected, set to 'none'.
    lws: float or list of floats
        Widths of the connecting lines.
    markers: 2-tuple or list of 2-tuples
        For each point style a marker. The first element of the inner tuple is
        the marker symbol, the second one is a factor that is used to scale
        the marker's size.
    markersizes: float or list of floats
        For each point style a marker size. The marker size is multiplied with a factor
        of the corresponding marker.
    medgecolors: float or list of floats
        Defines the edge color for each point style.
        It is passed as the lightness argument to `lighter()`
        using the face color form `colors`. That is, 0 results in a white edge color,
        1 in an edge with the same color as the face color, and 2 in a black edge color.
    markersizes: float, list of floats
        For each point style a marker edge width.
    namespace: dict or None
        Namespace to which the generated point styles are added.
        If None add point styles to the __main__ module.
    kwargs: dict
        Key-word arguments with further marker properties, e.g. alpha, zorder.
    """
    # prepare dictionaries:
    if namespace is None:
        namespace = __main__
    if not hasattr(namespace, 'style_names'):
        namespace.style_names = []
    if not isinstance(suffix, (tuple, list)):
        suffix = [suffix]
    for sf in suffix:
        ln = prefix + sf
        if not hasattr(namespace, ln):
            setattr(namespace, ln, {})
    # number of markers:
    n_markers = 1
    if len(markers) >= 2 and isinstance(markers[1], (tuple, list)):
        n_markers = len(markers)
    # number of line styles to be generated:
    n = 1
    for x in (names, suffix, colors, dashes, lws, markersizes,
              markeredgecolors, markeredgewidths):
        if isinstance(x, (tuple, list)) and len(x) > n:
            n = len(x)
    if n < n_markers:
        n = n_markers
    # generate styles:
    for k in range(n):
        if isinstance(names, (tuple, list)):
            name = names[k]
        else:
            if '%' in names:
                name = names % (k + 1)
            else:
                name = names
        if name not in namespace.style_names:
            namespace.style_names.append(name)
        sf = suffix[k % len(suffix)]
        c = colors[k] if isinstance(colors, (tuple, list)) else colors
        ds = dashes[k] if isinstance(dashes, (tuple, list)) else dashes
        lw = lws[k] if isinstance(lws, (tuple, list)) else lws
        mk = markers[k] if n_markers > 1 else markers
        ms = markersizes[k] if isinstance(markersizes,
                                          (tuple, list)) else markersizes
        mc = markeredgecolors[k] if isinstance(markeredgecolors,
                                               (tuple,
                                                list)) else markeredgecolors
        mw = markeredgewidths[k] if isinstance(markeredgewidths,
                                               (tuple,
                                                list)) else markeredgewidths
        pd = dict(color=c,
                  linestyle=ds,
                  linewidth=lw,
                  marker=mk[0],
                  markersize=mk[1] * ms,
                  markeredgecolor=lighter(c, mc),
                  markeredgewidth=mw,
                  **kwargs)
        setattr(namespace, prefix + name + sf, pd)
        getattr(namespace, ln)[prefix + sf] = pd