python 数据统计 pie绘图函数使用

import matplotlib.pyplot as plt

labels = ['Major Match', '']
sizes = [273, 727]
colors = ['#E2E2E2', '#6392BF']
explode = (0, 0.08)
plt.figure(figsize=(7, 7))
plt.pie(sizes,
        labels=labels,
        explode=explode,
        autopct='%1.1f%%',
        colors=colors,
        startangle=270,
        shadow=True)
plt.savefig('major-match-job.png', transparent=True)
plt.show()

代码来源:https://github.com/selfteaching/the-craft-of-selfteaching/blob/master/markdown/Part.1.A.better.teachyourself.md

函数pie源代码如下:

pie函数声明

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
@_autogen_docstring(Axes.pie)
def pie(x, explode=None, labels=None, colors=None, autopct=None,
        pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
        radius=None, counterclock=True, wedgeprops=None, textprops=None,
        center=(0, 0), frame=False, rotatelabels=False, hold=None, data=None):
    ax = gca()
    # Deprecated: allow callers to override the hold state
    # by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.pie(x, explode=explode, labels=labels, colors=colors,
                     autopct=autopct, pctdistance=pctdistance, shadow=shadow,
                     labeldistance=labeldistance, startangle=startangle,
                     radius=radius, counterclock=counterclock,
                     wedgeprops=wedgeprops, textprops=textprops, center=center,
                     frame=frame, rotatelabels=rotatelabels, data=data)
    finally:
        ax._hold = washold

    return ret

pip函数实现

def pie(self, x, explode=None, labels=None, colors=None,
        autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1,
        startangle=None, radius=None, counterclock=True,
        wedgeprops=None, textprops=None, center=(0, 0),
        frame=False, rotatelabels=False):
    """
    Plot a pie chart. 画一个饼状图

    Make a pie chart of array *x*.  The fractional area of each wedge is
    given by ``x/sum(x)``.  If ``sum(x) < 1``, then the values of *x* give
    the fractional area directly and the array will not be normalized. The
    resulting pie will have an empty wedge of size ``1 - sum(x)``.

    The wedges are plotted counterclockwise, by default starting from the
    x-axis.

    Parameters
    ----------
    x : array-like
        The wedge sizes.

    explode : array-like, optional, default: None
        If not *None*, is a ``len(x)`` array which specifies the fraction
        of the radius with which to offset each wedge.

    labels : list, optional, default: None
        A sequence of strings providing the labels for each wedge

    colors : array-like, optional, default: None
        A sequence of matplotlib color args through which the pie chart
        will cycle.  If *None*, will use the colors in the currently
        active cycle.

    autopct : None (default), string, or function, optional
        If not *None*, is a string or function used to label the wedges
        with their numeric value.  The label will be placed inside the
        wedge.  If it is a format string, the label will be ``fmt%pct``.
        If it is a function, it will be called.

    pctdistance : float, optional, default: 0.6
        The ratio between the center of each pie slice and the start of
        the text generated by *autopct*.  Ignored if *autopct* is *None*.

    shadow : bool, optional, default: False
        Draw a shadow beneath the pie.

    labeldistance : float, optional, default: 1.1
        The radial distance at which the pie labels are drawn

    startangle : float, optional, default: None
        If not *None*, rotates the start of the pie chart by *angle*
        degrees counterclockwise from the x-axis.

    radius : float, optional, default: None
        The radius of the pie, if *radius* is *None* it will be set to 1.

    counterclock : bool, optional, default: True
        Specify fractions direction, clockwise or counterclockwise.

    wedgeprops : dict, optional, default: None
        Dict of arguments passed to the wedge objects making the pie.
        For example, you can pass in ``wedgeprops = {'linewidth': 3}``
        to set the width of the wedge border lines equal to 3.
        For more details, look at the doc/arguments of the wedge object.
        By default ``clip_on=False``.

    textprops : dict, optional, default: None
        Dict of arguments to pass to the text objects.

    center :  list of float, optional, default: (0, 0)
        Center position of the chart. Takes value (0, 0) or is a sequence
        of 2 scalars.

    frame : bool, optional, default: False
        Plot axes frame with the chart if true.

    rotatelabels : bool, optional, default: False
        Rotate each label to the angle of the corresponding slice if true.

    Returns
    -------
    patches : list
        A sequence of :class:`matplotlib.patches.Wedge` instances

    texts : list
        A list of the label :class:`matplotlib.text.Text` instances.

    autotexts : list
        A list of :class:`~matplotlib.text.Text` instances for the numeric
        labels. This will only be returned if the parameter *autopct* is
        not *None*.

    Notes
    -----
    The pie chart will probably look best if the figure and axes are
    square, or the Axes aspect is equal.
    """
    x = np.array(x, np.float32)

    sx = x.sum()
    if sx > 1:
        x /= sx

    if labels is None:
        labels = [''] * len(x)
    if explode is None:
        explode = [0] * len(x)
    if len(x) != len(labels):
        raise ValueError("'label' must be of length 'x'")
    if len(x) != len(explode):
        raise ValueError("'explode' must be of length 'x'")
    if colors is None:
        get_next_color = self._get_patches_for_fill.get_next_color
    else:
        color_cycle = itertools.cycle(colors)

        def get_next_color():
            return next(color_cycle)

    if radius is None:
        radius = 1

    # Starting theta1 is the start fraction of the circle
    if startangle is None:
        theta1 = 0
    else:
        theta1 = startangle / 360.0

    # set default values in wedge_prop
    if wedgeprops is None:
        wedgeprops = {}
    wedgeprops.setdefault('clip_on', False)

    if textprops is None:
        textprops = {}
    textprops.setdefault('clip_on', False)

    texts = []
    slices = []
    autotexts = []

    i = 0
    for frac, label, expl in zip(x, labels, explode):
        x, y = center
        theta2 = (theta1 + frac) if counterclock else (theta1 - frac)
        thetam = 2 * np.pi * 0.5 * (theta1 + theta2)
        x += expl * math.cos(thetam)
        y += expl * math.sin(thetam)

        w = mpatches.Wedge((x, y), radius, 360. * min(theta1, theta2),
                           360. * max(theta1, theta2),
                           facecolor=get_next_color(),
                           **wedgeprops)
        slices.append(w)
        self.add_patch(w)
        w.set_label(label)

        if shadow:
            # make sure to add a shadow after the call to
            # add_patch so the figure and transform props will be
            # set
            shad = mpatches.Shadow(w, -0.02, -0.02)
            shad.set_zorder(0.9 * w.get_zorder())
            shad.set_label('_nolegend_')
            self.add_patch(shad)

        xt = x + labeldistance * radius * math.cos(thetam)
        yt = y + labeldistance * radius * math.sin(thetam)
        label_alignment_h = xt > 0 and 'left' or 'right'
        label_alignment_v = 'center'
        label_rotation = 'horizontal'
        if rotatelabels:
            label_alignment_v = yt > 0 and 'bottom' or 'top'
            label_rotation = np.rad2deg(thetam) + (0 if xt > 0 else 180)

        t = self.text(xt, yt, label,
                      size=rcParams['xtick.labelsize'],
                      horizontalalignment=label_alignment_h,
                      verticalalignment=label_alignment_v,
                      rotation=label_rotation,
                      **textprops)

        texts.append(t)

        if autopct is not None:
            xt = x + pctdistance * radius * math.cos(thetam)
            yt = y + pctdistance * radius * math.sin(thetam)
            if isinstance(autopct, six.string_types):
                s = autopct % (100. * frac)
            elif callable(autopct):
                s = autopct(100. * frac)
            else:
                raise TypeError(
                    'autopct must be callable or a format string')

            t = self.text(xt, yt, s,
                          horizontalalignment='center',
                          verticalalignment='center',
                          **textprops)

            autotexts.append(t)

        theta1 = theta2
        i += 1

    if not frame:
        self.set_frame_on(False)

        self.set_xlim((-1.25 + center[0],
                       1.25 + center[0]))
        self.set_ylim((-1.25 + center[1],
                       1.25 + center[1]))
        self.set_xticks([])
        self.set_yticks([])

    if autopct is None:
        return slices, texts
    else:
        return slices, texts, autotexts

 

 

你可能感兴趣的:(python学习可视化,pie,phton)