Beispiel #1
0
def ggsize(width, height):
    """
    Specify overall size of plot.

    Parameters
    ----------
    width : int
        Width of plot in px.
    height : int
        Height of plot in px.

    Returns
    -------
    `FeatureSpec`
        Plot size specification.

    Examples
    --------
    .. jupyter-execute::
        :linenos:
        :emphasize-lines: 8

        import numpy as np
        from lets_plot import *
        LetsPlot.setup_html()
        np.random.seed(42)
        x = np.arange(50)
        y = np.random.normal(size=50)
        data = {'x': x, 'y': y}
        ggplot(data) + geom_line(aes('x', 'y')) + ggsize(400, 150)

    """
    assert isinstance(width, numbers.Number), "'width' must be numeric"
    assert isinstance(height, numbers.Number), "'height' must be numeric"

    max_width = get_global_val(MAX_WIDTH) if has_global_value(
        MAX_WIDTH) else 10_000
    max_height = get_global_val(MAX_HEIGHT) if has_global_value(
        MAX_HEIGHT) else 10_000

    assert width <= max_width, "'width' must be less than or equal to " + str(
        max_width)
    assert height <= max_height, "'height' must be less than or equal to " + str(
        max_height)

    return FeatureSpec('ggsize', name=None, width=width, height=height)
Beispiel #2
0
def _prepare_geocoding():
    if has_global_value(GEOCODING_PROVIDER_URL):
        return {
            OPTIONS_GEOCODING_PROVIDER_URL:
            get_global_val(GEOCODING_PROVIDER_URL) + GEOCODING_ROUTE
        }

    return {}
Beispiel #3
0
    def before_append(self, is_livemap):
        from .util import normalize_map_join, is_geo_data_frame, auto_join_geo_names, geo_data_frame_to_wgs84, \
            get_geo_data_frame_meta
        from lets_plot.geo_data_internals.utils import is_geocoder

        name = self.props().get('geom', None)
        map_join = self.props().get('map_join', None)
        map = self.props().get('map', None)
        map_data_meta = None

        if map_join is None and map is None:
            return

        map_join = normalize_map_join(map_join)

        if is_geocoder(map):
            if is_livemap and get_global_bool(
                    FRAGMENTS_ENABLED) if has_global_value(
                        FRAGMENTS_ENABLED) else False:
                map = map.get_geocodes()
                map_join = auto_join_geo_names(map_join, map)
                map_data_meta = {'georeference': {}}
            else:
                # Fetch proper GeoDataFrame. Further processing is the same as if map was a GDF.
                if name in ['point', 'text', 'livemap']:
                    map = map.get_centroids()
                elif name in ['map', 'polygon']:
                    map = map.get_boundaries()
                elif name in ['rect']:
                    map = map.get_limits()
                else:
                    raise ValueError(
                        "Geocoding doesn't provide geometries for geom_{}".
                        format(name))

        if is_geo_data_frame(map):
            map = geo_data_frame_to_wgs84(map)
            map_join = auto_join_geo_names(map_join, map)
            map_data_meta = get_geo_data_frame_meta(map)

        if map_join is not None:
            self.props()['map_join'] = map_join

        if map is not None:
            self.props()['map'] = map

        if map_data_meta is not None:
            self.props()['map_data_meta'] = map_data_meta
Beispiel #4
0
def ggplot(data=None, mapping=None):
    """
    Create a new ggplot plot.

    Parameters
    ----------
    data : dict or `DataFrame`
        Default dataset to use for the plot. If not specified,
        must be supplied in each layer added to the plot.
    mapping : `FeatureSpec`
        Default list of aesthetic mappings to use for the plot.
        If not specified, must be supplied in each layer added to the plot.

    Returns
    -------
    `PlotSpec`
        Plot specification.

    Notes
    -----
    `ggplot()` initializes a ggplot object.
    It can be used to declare the input data frame for a graphic and
    to specify the set of plot aesthetics intended to be common
    throughout all subsequent layers unless specifically overridden.

    `ggplot()` is typically used to construct a plot incrementally,
    using the + operator to add layers to the existing ggplot object.
    This is advantageous in that the code is explicit about which layers
    are added and the order in which they are added. For complex graphics
    with multiple layers, initialization with `ggplot()` is recommended.

    There are three common ways to invoke ggplot (see examples below):

    - `ggplot(data, aes(x, y))`: This method is recommended if all layers use the same data and the same set of aesthetics, although this method can also be used to add a layer using data from another data frame.
    - `ggplot(data)`: This method specifies the default data frame to use for the plot, but no aesthetics are defined up front. This is useful when one data frame is used predominantly as layers are added, but the aesthetics may vary from one layer to another.
    - `ggplot()`: This method initializes a skeleton ggplot object which is fleshed out as layers are added. This method is useful when multiple data frames are used to produce different layers, as is often the case in complex graphics.

    `ggplot()` with no layers defined will produce an error message:
    "No layers in plot".

    Examples
    --------
    .. jupyter-execute::
        :linenos:
        :emphasize-lines: 11, 13, 15

        import numpy as np
        from lets_plot import *
        LetsPlot.setup_html()
        np.random.seed(42)
        n = 100
        x = np.random.uniform(-1, 1, size=n)
        y = np.random.normal(size=n)
        data = {'x': x, 'y': 25 * x ** 2 + y}
        # three ways to invoke ggplot, producing the same output:
        # (1)
        ggplot(data, aes(x='x', y='y')) + geom_point()
        # (2)
        ggplot(data) + geom_point(aes(x='x', y='y'))
        # (3)
        ggplot() + geom_point(aes(x='x', y='y'), data=data)

    """
    if isinstance(data, FeatureSpec):
        raise ValueError(
            "Object {!r} is not acceptable as 'data' argument in ggplot()".
            format(data.kind))

    if is_geocoder(data):
        data = data.get_geocodes()

    data, mapping, data_meta = as_annotated_data(data, mapping)

    plot_spec = PlotSpec(data, mapping, scales=[], layers=[], **data_meta)

    if has_global_value(PLOT_THEME):
        theme_options = json.loads(get_global_val(PLOT_THEME))
        theme_name = theme_options.pop('name', None)
        plot_spec += FeatureSpec('theme', theme_name, **theme_options)

    return plot_spec
Beispiel #5
0
def _prepare_tiles(tiles: Optional[Union[str, dict]]) -> Optional[dict]:
    if isinstance(tiles, str):
        return {
            OPTIONS_MAPTILES_KIND: TILES_RASTER_ZXY,
            OPTIONS_MAPTILES_URL: tiles
        }

    if isinstance(tiles, dict):
        if tiles.get(MAPTILES_KIND, None) == TILES_RASTER_ZXY:
            return {
                OPTIONS_MAPTILES_KIND: TILES_RASTER_ZXY,
                OPTIONS_MAPTILES_URL: tiles[MAPTILES_URL],
                OPTIONS_MAPTILES_ATTRIBUTION: tiles[MAPTILES_ATTRIBUTION],
                OPTIONS_MAPTILES_MIN_ZOOM: tiles[MAPTILES_MIN_ZOOM],
                OPTIONS_MAPTILES_MAX_ZOOM: tiles[MAPTILES_MAX_ZOOM],
            }
        elif tiles.get(MAPTILES_KIND, None) == TILES_VECTOR_LETS_PLOT:
            return {
                OPTIONS_MAPTILES_KIND: TILES_VECTOR_LETS_PLOT,
                OPTIONS_MAPTILES_URL: tiles[MAPTILES_URL],
                OPTIONS_MAPTILES_THEME: tiles[MAPTILES_THEME],
                OPTIONS_MAPTILES_ATTRIBUTION: tiles[MAPTILES_ATTRIBUTION],
            }
        elif tiles.get(MAPTILES_KIND, None) == TILES_SOLID:
            return {
                OPTIONS_MAPTILES_KIND: TILES_SOLID,
                OPTIONS_MAPTILES_FILL_COLOR: tiles[MAPTILES_SOLID_FILL_COLOR]
            }
        elif tiles.get(MAPTILES_KIND, None) == TILES_CHESSBOARD:
            return {OPTIONS_MAPTILES_KIND: TILES_CHESSBOARD}
        else:
            raise ValueError("Unsupported 'tiles' kind: " +
                             tiles.get(MAPTILES_KIND, None))

    if tiles is not None:
        raise ValueError("Unsupported 'tiles' parameter type: " + type(tiles))

    # tiles are not set for this livemap - try to get global tiles config
    if has_global_value(MAPTILES_KIND):
        if not has_global_value(MAPTILES_URL):
            raise ValueError('URL for tiles service is not set')

        if get_global_val(MAPTILES_KIND) == TILES_RASTER_ZXY:
            return {
                OPTIONS_MAPTILES_KIND:
                TILES_RASTER_ZXY,
                OPTIONS_MAPTILES_URL:
                get_global_val(MAPTILES_URL),
                OPTIONS_MAPTILES_ATTRIBUTION:
                get_global_val(MAPTILES_ATTRIBUTION)
                if has_global_value(MAPTILES_ATTRIBUTION) else None,
                OPTIONS_MAPTILES_MIN_ZOOM:
                get_global_val(MAPTILES_MIN_ZOOM)
                if has_global_value(MAPTILES_MIN_ZOOM) else None,
                OPTIONS_MAPTILES_MAX_ZOOM:
                get_global_val(MAPTILES_MAX_ZOOM)
                if has_global_value(MAPTILES_MAX_ZOOM) else None,
            }

        if get_global_val(MAPTILES_KIND) == TILES_VECTOR_LETS_PLOT:
            return {
                OPTIONS_MAPTILES_KIND:
                TILES_VECTOR_LETS_PLOT,
                OPTIONS_MAPTILES_URL:
                get_global_val(MAPTILES_URL),
                OPTIONS_MAPTILES_THEME:
                get_global_val(MAPTILES_THEME)
                if has_global_value(MAPTILES_THEME) else None,
                OPTIONS_MAPTILES_ATTRIBUTION:
                get_global_val(MAPTILES_ATTRIBUTION)
                if has_global_value(MAPTILES_ATTRIBUTION) else None,
            }

        if get_global_val(MAPTILES_KIND) == TILES_SOLID:
            return {
                OPTIONS_MAPTILES_KIND:
                TILES_SOLID,
                OPTIONS_MAPTILES_FILL_COLOR:
                get_global_val(MAPTILES_SOLID_FILL_COLOR),
            }

    raise ValueError('Tile provider is not set.')