How to use plotnine - 10 common examples

To help you get started, we’ve selected a few plotnine 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 has2k1 / plotnine / plotnine / scales / scale.py View on Github external
def __init__(self, **kwargs):
        for k, v in kwargs.items():
            if hasattr(self, k):
                setattr(self, k, v)
            else:
                msg = "{} could not recognise parameter `{}`"
                warn(msg.format(self.__class__.__name__, k), PlotnineWarning)

        self.range = self._range_class()

        if np.iterable(self.breaks) and np.iterable(self.labels):
            if len(self.breaks) != len(self.labels):
                raise PlotnineError(
                    "Breaks and labels have unequal lengths")

        if (self.breaks is None and
                not is_position_aes(self.aesthetics) and
                self.guide is not None):
            self.guide = None
github has2k1 / plotnine / plotnine / animation.py View on Github external
"""
            if len(scale_limits) != len(plot.scales):
                raise PlotnineError(
                    "All plots must have the same number of scales "
                    "as the first plot of the animation."
                )

            for sc in plot.scales:
                ae = sc.aesthetics[0]
                if ae not in scale_limits:
                    raise PlotnineError(
                        "The plot for frame {} does not have a scale "
                        "for the {} aesthetic.".format(frame_no, ae)
                    )
                if sc.limits != scale_limits[ae]:
                    raise PlotnineError(
                        "The {} scale of plot for frame {} has different "
                        "limits from those of the first frame."
                        "".format(ae, frame_no)
                    )
github has2k1 / plotnine / plotnine / themes / themeable.py View on Github external
def rcParams(self):
        rcParams = super(figure_size, self).rcParams
        try:
            width, height = self.properties['value']
        except ValueError:
            raise PlotnineError(
                'figure_size should be a tuple (width, height) '
                'with the values in inches')

        rcParams['figure.figsize'] = '{}, {}'.format(width,
                                                     height)
        return rcParams
github has2k1 / plotnine / plotnine / qplot.py View on Github external
def get_facet_type(facets):
        with suppress(PlotnineError):
            parse_grid_facets(facets)
            return 'grid'

        with suppress(PlotnineError):
            parse_wrap_facets(facets)
            return 'wrap'

        warn("Could not determine the type of faceting, "
             "therefore no faceting.", PlotnineWarning)
        return 'null'
github has2k1 / plotnine / plotnine / geoms / geom.py View on Github external
for ae in missing_aes:
            data[ae] = self.DEFAULT_AES[ae]

        # If set, use it
        for ae, value in self.aes_params.items():
            try:
                data[ae] = value
            except ValueError:
                # sniff out the special cases, like custom
                # tupled linetypes, shapes and colors
                if is_valid_aesthetic(value, ae):
                    data[ae] = [value]*len(data)
                else:
                    msg = ("'{}' does not look like a "
                           "valid value for `{}`")
                    raise PlotnineError(msg.format(value, ae))

        return data
github has2k1 / plotnine / plotnine / utils.py View on Github external
# check args #
    if mapping is not None and not isinstance(mapping, aes):
        raise PlotnineError(
            "Unknown mapping of type {}".format(type(mapping))
        )

    if data is not None and not isinstance(data, pd.DataFrame):
        raise PlotnineError(
            "Unknown data of type {}".format(type(mapping))
        )

    # check kwargs #
    if mapping is not None:
        if 'mapping' in kwargs:
            raise PlotnineError("More than one mapping argument.")
        else:
            kwargs['mapping'] = mapping
    else:
        if 'mapping' not in kwargs:
            mapping = aes()

    if kwargs.get('mapping', None) is None:
        kwargs['mapping'] = mapping

    if data is not None and 'data' in kwargs:
        raise PlotnineError("More than one data argument.")
    elif 'data' not in kwargs:
        kwargs['data'] = data

    duplicates = set(kwargs['mapping']) & set(kwargs)
    if duplicates:
github has2k1 / plotnine / plotnine / positions / position.py View on Github external
intervals = data[xminmax].drop_duplicates().values.flatten()
        intervals = intervals[~np.isnan(intervals)]

        if (len(np.unique(intervals)) > 1 and
                any(np.diff(intervals - intervals.mean()) < -1e-6)):
            msg = "{} requires non-overlapping x intervals"
            warn(msg.format(cls.__name__), PlotnineWarning)

        if 'ymax' in data:
            data = groupby_apply(data, 'xmin', cls.strategy, params)
        elif 'y' in data:
            data['ymax'] = data['y']
            data = groupby_apply(data, 'xmin', cls.strategy, params)
            data['y'] = data['ymax']
        else:
            raise PlotnineError('Neither y nor ymax defined')

        return data
github has2k1 / plotnine / plotnine / layer.py View on Github external
# of the ggplot.data. If the has data it is replaced
        # by copy so that we do not alter the users data
        if self.data is None:
            try:
                self.data = plot_data.copy()
            except AttributeError:
                _geom_name = self.geom.__class__.__name__
                _data_name = plot_data.__class__.__name__
                raise PlotnineError(
                    "{} layer expects a dataframe, but it got "
                    "{} instead.".format(_geom_name, _data_name)
                )
        elif hasattr(self.data, '__call__'):
            self.data = self.data(plot_data)
            if not isinstance(self.data, pd.DataFrame):
                raise PlotnineError(
                    "Data function must return a dataframe")
        else:
            self.data = self.data.copy()
github has2k1 / plotnine / plotnine / positions / position_dodge.py View on Github external
def setup_params(self, data):
        if (('xmin' not in data) and
                ('xmax' not in data) and
                (self.params['width'] is None)):
            msg = ("Width not defined. "
                   "Set with `position_dodge(width = ?)`")
            raise PlotnineError(msg)

        params = copy(self.params)

        if params['preserve'] == 'total':
            params['n'] = None
        else:
            # Count at the xmin values per panel and find the highest
            # overall count
            def max_xmin_values(gdf):
                n = gdf['xmin'].value_counts().max()
                return pd.DataFrame({'n': [n]})

            res = groupby_apply(data, 'PANEL', max_xmin_values)
            params['n'] = res['n'].max()
        return params
github has2k1 / plotnine / plotnine / guides / guide_legend.py View on Github external
def _set_defaults(self):
        guide._set_defaults(self)

        nbreak = len(self.key)

        # rows and columns
        if self.nrow is not None and self.ncol is not None:
            if guide.nrow * guide.ncol < nbreak:
                raise PlotnineError(
                    "nrow x ncol need to be larger",
                    "than the number of breaks")

        if self.nrow is None and self.ncol is None:
            if self.direction == 'horizontal':
                self.nrow = int(np.ceil(nbreak/5))
            else:
                self.ncol = int(np.ceil(nbreak/20))

        self.nrow = self.nrow or int(np.ceil(nbreak/self.ncol))
        self.ncol = self.ncol or int(np.ceil(nbreak/self.nrow))

        # key width and key height for each legend entry
        #
        # Take a peak into data['size'] to make sure the
        # legend dimensions are big enough