예제 #1
0
def histogram_of_every_row(counts_col, **kwargs):
    """
    Plots the histogram of every row in a dataframe, overlaying them.
    Meant to be used within a map_dataframe call.

    Implementation inspired in https://matplotlib.org/gallery/api/histogram_path.html

    :param df: Dataframe
    :param counts_col: Name of the counts column
    :param edges_col: Name of the edges column
    :param ax: Matplotlib axis object
    :return:
    """
    ax = plt.gca()
    edges_col = kwargs.pop(
        "edges_col") if "edges_col" in kwargs else "hist_edges"
    data = kwargs.pop("data")
    color = kwargs.pop("color")
    label = kwargs.pop("label") if "label" in kwargs else None

    # FIXME: Find a way to increase opacity resolution
    min_op = 1. / 256.
    opacity = 1. / len(data)
    opacity = opacity if opacity >= min_op else min_op
    logger.info("plotting %d histograms overlaid with opacity %e." %
                (len(data), opacity))

    # get the corners of the rectangles for the histogram
    bins = data[edges_col].iloc[0]
    left = np.array(bins[:-1])
    right = np.array(bins[1:])
    bottom = np.zeros(len(left))

    for _ix, _d in data.iterrows():
        counts = _d[counts_col]
        top = bottom + counts

        # function to build a compound path
        XY = np.array([[left, left, right, right], [bottom, top, top,
                                                    bottom]]).T

        # get the Path object
        barpath = Path.make_compound_path_from_polys(XY)

        # make a patch out of it
        patch = PathPatch(barpath, alpha=opacity, lw=0, color=color)
        ax.add_patch(patch)

    ax.xaxis.set_major_locator(ticker.LogLocator(base=10))
    ax.xaxis.set_major_formatter(ticker.LogFormatterMathtext(base=10))
    ax.yaxis.set_major_formatter(EngFormatter(unit=''))
    ax.set_xlim(left[0], right[-1])
    ax.set_ylim(bottom.min(),
                data[counts_col].apply(lambda r: np.max(r)).max())
예제 #2
0
파일: models.py 프로젝트: ajun73/Work_Code
def plot_ellipses_MacAdam1942_in_chromaticity_diagram(
        chromaticity_diagram_callable=plot_chromaticity_diagram,
        method='CIE 1931',
        chromaticity_diagram_clipping=False,
        ellipse_parameters=None,
        **kwargs):
    """
    Plots *MacAdam (1942) Ellipses (Observer PGN)* in the
    *Chromaticity Diagram* according to given method.

    Parameters
    ----------
    chromaticity_diagram_callable : callable, optional
        Callable responsible for drawing the *Chromaticity Diagram*.
    method : unicode, optional
        **{'CIE 1931', 'CIE 1960 UCS', 'CIE 1976 UCS'}**,
        *Chromaticity Diagram* method.
    chromaticity_diagram_clipping : bool, optional,
        Whether to clip the *Chromaticity Diagram* colours with the ellipses.
    ellipse_parameters : dict or array_like, optional
        Parameters for the :class:`Ellipse` class, ``ellipse_parameters`` can
        be either a single dictionary applied to all the ellipses with same
        settings or a sequence of dictionaries with different settings for each
        ellipse.

    Other Parameters
    ----------------
    \\**kwargs : dict, optional
        {:func:`colour.plotting.artist`,
        :func:`colour.plotting.diagrams.plot_chromaticity_diagram`,
        :func:`colour.plotting.render`},
        Please refer to the documentation of the previously listed definitions.

    Returns
    -------
    tuple
        Current figure and axes.

    Examples
    --------
    >>> plot_ellipses_MacAdam1942_in_chromaticity_diagram()  # doctest: +SKIP

    .. image:: ../_static/\
Plotting_Plot_Ellipses_MacAdam1942_In_Chromaticity_Diagram.png
        :align: center
        :alt: plot_ellipses_MacAdam1942_in_chromaticity_diagram
    """

    settings = {'uniform': True}
    settings.update(kwargs)

    figure, axes = artist(**settings)

    settings = dict(kwargs)
    settings.update({'axes': axes, 'standalone': False})

    ellipses_coefficients = ellipses_MacAdam1942(method=method)

    if chromaticity_diagram_clipping:
        diagram_clipping_path_x = []
        diagram_clipping_path_y = []
        for coefficients in ellipses_coefficients:
            coefficients = np.copy(coefficients)

            coefficients[2:4] /= 2

            x, y = tsplit(
                point_at_angle_on_ellipse(
                    np.linspace(0, 360, 36),
                    coefficients,
                ))
            diagram_clipping_path_x.append(x)
            diagram_clipping_path_y.append(y)

        diagram_clipping_path = np.rollaxis(
            np.array([diagram_clipping_path_x, diagram_clipping_path_y]), 0, 3)
        diagram_clipping_path = Path.make_compound_path_from_polys(
            diagram_clipping_path).vertices
        settings.update({'diagram_clipping_path': diagram_clipping_path})

    chromaticity_diagram_callable(**settings)

    ellipse_settings_collection = [{
        'color':
        COLOUR_STYLE_CONSTANTS.colour.cycle[4],
        'alpha':
        0.4,
        'edgecolor':
        COLOUR_STYLE_CONSTANTS.colour.cycle[1],
        'linewidth':
        colour_style()['lines.linewidth']
    } for _ in range(len(ellipses_coefficients))]

    if ellipse_parameters is not None:
        if not isinstance(ellipse_parameters, dict):
            assert len(ellipse_parameters) == len(ellipses_coefficients), (
                'Multiple ellipse parameters defined, but they do not match '
                'the ellipses count!')

        for i, ellipse_settings in enumerate(ellipse_settings_collection):
            if isinstance(ellipse_parameters, dict):
                ellipse_settings.update(ellipse_parameters)
            else:
                ellipse_settings.update(ellipse_parameters[i])

    for i, coefficients in enumerate(ellipses_coefficients):
        x_c, y_c, a_a, a_b, theta_e = coefficients
        ellipse = Ellipse((x_c, y_c), a_a, a_b, theta_e,
                          **ellipse_settings_collection[i])
        axes.add_artist(ellipse)

    settings.update({'standalone': True})
    settings.update(kwargs)

    return render(**settings)
예제 #3
0
파일: sde.py 프로젝트: schruste/ngsapps
def makeV(apex, angle, openingAngle, length, thickness):
    verts = [apex]
    verts.append(verts[-1] + length*vec(cos(angle-openingAngle/2), sin(angle-openingAngle/2)))
    verts.append(verts[-1] + thickness*vec(cos(angle-openingAngle/2+pi/2), sin(angle-openingAngle/2+pi/2)))
    verts.append(verts[-1] - (length-thickness/tan(openingAngle/2))*vec(cos(angle-openingAngle/2), sin(angle-openingAngle/2)))
    verts.append(verts[-1] + (length-thickness/tan(openingAngle/2))*vec(cos(angle+openingAngle/2), sin(angle+openingAngle/2)))
    verts.append(verts[-1] + thickness*vec(cos(angle+openingAngle/2+pi/2), sin(angle+openingAngle/2+pi/2)))
    return verts

polys = []
for i in range(3):
    for j in range(8):
        polys.append(makeV((200*sigma + i*280*sigma, j*(60+9)*sigma), 0, pi/3, 60*sigma, 10*sigma))
        polys.append(makeV((xmax - 200*sigma - i*280*sigma, j*(60+9)*sigma), pi, pi/3, 60*sigma, 10*sigma))
path = Path.make_compound_path_from_polys(np.array(polys))

# local swim speed
def v(i, inPoly):
    if inPoly[i]:
        return 0
    else:
        return v0

thetas = np.zeros(N)
xs = xmin + Lx*rnd.rand(N)
ys = ymin + Ly*rnd.rand(N)
points = np.array(list(zip(xs, ys)))

fig, ax = plt.subplots()
ax.set_xlim(xmin, xmax)
예제 #4
0
def plot_ellipses_MacAdam1942_in_chromaticity_diagram(
        chromaticity_diagram_callable=plot_chromaticity_diagram,
        method='CIE 1931',
        chromaticity_diagram_clipping=False,
        ellipse_parameters=None,
        **kwargs):
    """
    Plots *MacAdam (1942) Ellipses (Observer PGN)* in the
    *Chromaticity Diagram* according to given method.

    Parameters
    ----------
    chromaticity_diagram_callable : callable, optional
        Callable responsible for drawing the *Chromaticity Diagram*.
    method : unicode, optional
        **{'CIE 1931', 'CIE 1960 UCS', 'CIE 1976 UCS'}**,
        *Chromaticity Diagram* method.
    chromaticity_diagram_clipping : bool, optional,
        Whether to clip the *Chromaticity Diagram* colours with the ellipses.
    ellipse_parameters : dict or array_like, optional
        Parameters for the :class:`Ellipse` class, ``ellipse_parameters`` can
        be either a single dictionary applied to all the ellipses with same
        settings or a sequence of dictionaries with different settings for each
        ellipse.

    Other Parameters
    ----------------
    \\**kwargs : dict, optional
        {:func:`colour.plotting.artist`,
        :func:`colour.plotting.diagrams.plot_chromaticity_diagram`,
        :func:`colour.plotting.render`},
        Please refer to the documentation of the previously listed definitions.

    Returns
    -------
    tuple
        Current figure and axes.

    Examples
    --------
    >>> plot_ellipses_MacAdam1942_in_chromaticity_diagram()  # doctest: +SKIP

    .. image:: ../_static/\
Plotting_Plot_Ellipses_MacAdam1942_In_Chromaticity_Diagram.png
        :align: center
        :alt: plot_ellipses_MacAdam1942_in_chromaticity_diagram
    """

    settings = {'uniform': True}
    settings.update(kwargs)

    _figure, axes = artist(**settings)

    settings = dict(kwargs)
    settings.update({'axes': axes, 'standalone': False})

    ellipses_coefficients = ellipses_MacAdam1942(method=method)

    if chromaticity_diagram_clipping:
        diagram_clipping_path_x = []
        diagram_clipping_path_y = []
        for coefficients in ellipses_coefficients:
            coefficients = np.copy(coefficients)

            coefficients[2:4] /= 2

            x, y = tsplit(
                point_at_angle_on_ellipse(
                    np.linspace(0, 360, 36),
                    coefficients,
                ))
            diagram_clipping_path_x.append(x)
            diagram_clipping_path_y.append(y)

        diagram_clipping_path = np.rollaxis(
            np.array([diagram_clipping_path_x, diagram_clipping_path_y]), 0, 3)
        diagram_clipping_path = Path.make_compound_path_from_polys(
            diagram_clipping_path).vertices
        settings.update({'diagram_clipping_path': diagram_clipping_path})

    chromaticity_diagram_callable(**settings)

    ellipse_settings_collection = [{
        'color': COLOUR_STYLE_CONSTANTS.colour.cycle[4],
        'alpha': 0.4,
        'edgecolor': COLOUR_STYLE_CONSTANTS.colour.cycle[1],
        'linewidth': colour_style()['lines.linewidth']
    } for _ellipses_coefficient in ellipses_coefficients]

    if ellipse_parameters is not None:
        if not isinstance(ellipse_parameters, dict):
            assert len(ellipse_parameters) == len(ellipses_coefficients), (
                'Multiple ellipse parameters defined, but they do not match '
                'the ellipses count!')

        for i, ellipse_settings in enumerate(ellipse_settings_collection):
            if isinstance(ellipse_parameters, dict):
                ellipse_settings.update(ellipse_parameters)
            else:
                ellipse_settings.update(ellipse_parameters[i])

    for i, coefficients in enumerate(ellipses_coefficients):
        x_c, y_c, a_a, a_b, theta_e = coefficients
        ellipse = Ellipse((x_c, y_c), a_a, a_b, theta_e,
                          **ellipse_settings_collection[i])
        axes.add_artist(ellipse)

    settings.update({'standalone': True})
    settings.update(kwargs)

    return render(**settings)