当前位置: 首页>>代码示例>>Python>>正文


Python altair.Chart方法代码示例

本文整理汇总了Python中altair.Chart方法的典型用法代码示例。如果您正苦于以下问题:Python altair.Chart方法的具体用法?Python altair.Chart怎么用?Python altair.Chart使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在altair的用法示例。


在下文中一共展示了altair.Chart方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: visualize

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def visualize(display_df):
        viridis = ['#440154', '#472c7a', '#3b518b', '#2c718e', '#21908d', '#27ad81', '#5cc863', '#aadc32', '#fde725']
        import altair as alt
        color_scale = alt.Scale(
            domain=(display_df.dropna().trending.min(),
                    0,
                    display_df.dropna().trending.max()),
            range=[viridis[0], viridis[len(viridis) // 2], viridis[-1]]
        )

        return alt.Chart(display_df).mark_circle().encode(
            alt.X('variable'),
            alt.Y('term'),
            size='frequency',
            color=alt.Color('trending:Q', scale=color_scale),
        ) 
开发者ID:JasonKessler,项目名称:scattertext,代码行数:18,代码来源:BubbleDiachronicVisualization.py

示例2: altair_cluster_tsne

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def altair_cluster_tsne(data, clusters, target, plot_name=None, **kwargs):
    if hasattr(data.retention, '_tsne'):
        tsne = data.retention._tsne.copy()
    else:
        tsne = data.retention.learn_tsne(clusters, **kwargs)
    tsne['color'] = clusters
    tsne.columns = ['x', 'y', 'color']

    scatter = alt.Chart(tsne).mark_point().encode(
        x='x',
        y='y',
        color=alt.Color(
            'color',
            scale=alt.Scale(scheme='plasma')
        )
    ).properties(
        width=800,
        height=600
    )
    return scatter, plot_name, tsne, data.retention.retention_config 
开发者ID:retentioneering,项目名称:retentioneering-tools,代码行数:22,代码来源:plot.py

示例3: altair_cluster_bar

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def altair_cluster_bar(data, clusters, target, plot_name=None, plot_cnt=None, metrics=None, **kwargs):
    cl = pd.DataFrame([clusters, target], index=['clusters', 'target']).T
    cl['cnt'] = 1
    cl.target = cl.target.astype(int)
    bars = cl.groupby('clusters').agg({
        'cnt': 'sum',
        'target': 'mean'
    }).reset_index()
    bars.cnt /= bars.cnt.sum()
    bars = bars.loc[:, ['clusters', 'cnt']].append(bars.loc[:, ['clusters', 'target']], ignore_index=True, sort=False)
    bars['target'] = np.where(bars.target.isnull(), bars.cnt, bars.target)
    bars['Metric'] = np.where(bars['cnt'].isnull(), 'Average CR', 'Cluster size')
    # print(bars, type(bars))
    bar = alt.Chart(bars).mark_bar().encode(
        x='Metric:O',
        y='target:Q',
        color='Metric:N',
        column='clusters:N'
    ).properties(
        width=60,
        height=200
    )

    return bar, plot_name, None, data.retention.retention_config 
开发者ID:retentioneering,项目名称:retentioneering-tools,代码行数:26,代码来源:plot.py

示例4: plot

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def plot(self, show=True):
        kwargs = {
            e["encoding"]: _get_plot_command(e) for e in self.settings["encodings"]
        }
        kwargs = {k: v for k, v in kwargs.items() if v is not None}

        mark_opts = {k: v for k, v in self.settings["mark"].items()}
        mark = mark_opts.pop("mark")
        Chart_mark = getattr(altair.Chart(self.df), mark)
        self.chart = Chart_mark(**mark_opts).encode(**kwargs)
        if show and self.show:
            clear_output()
            display("Updating...")
            with io.StringIO() as f:
                self.chart.save(f, format="svg")
                f.seek(0)
                html = f.read()
            clear_output()
            display(self.controller)
            display(SVG(html)) 
开发者ID:altair-viz,项目名称:altair_widgets,代码行数:22,代码来源:widget.py

示例5: geoencode

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def geoencode(
        self, mode: str = "geometry"
    ) -> Optional[alt.Chart]:  # coverage: ignore

        if mode == "geometry":
            return (
                super().geoencode().mark_geoshape(strokeWidth=2, stroke="black")
            )

        elif mode == "labels":
            rwy_labels = alt.Chart(self.data).encode(
                longitude="longitude:Q", latitude="latitude:Q", text="name:N"
            )
            rwy_layers = [
                rwy_labels.transform_filter(alt.datum.name == name).mark_text(
                    angle=bearing, baseline="middle", dy=10
                )
                for (name, bearing) in zip(self.data.name, self.data.bearing)
            ]

            return alt.layer(*rwy_layers)

        else:
            return None 
开发者ID:xoolive,项目名称:traffic,代码行数:26,代码来源:runways.py

示例6: geoencode

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def geoencode(
        self,
        footprint: bool = True,
        runways: bool = False,
        labels: bool = False,
    ) -> alt.Chart:  # coverage: ignore
        cumul = []
        if footprint:
            cumul.append(super().geoencode())
        if runways:
            cumul.append(self.runways.geoencode())
        if labels:
            cumul.append(self.runways.geoencode("labels"))
        if len(cumul) == 0:
            raise TypeError(
                "At least one of footprint, runways and labels must be True"
            )
        return alt.layer(*cumul) 
开发者ID:xoolive,项目名称:traffic,代码行数:20,代码来源:structure.py

示例7: _get_chart_with_transform

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def _get_chart_with_transform(self):
        """Returns a chart object potentially with a URL transform added to it.

        Returns:
            A LayerChart object, either with added transform or not, depending
            on whether sketch URL and field are set.
        """
        chart = alt.Chart(self.values)
        if not self._sketch_url:
            return chart

        if not self._field:
            return chart

        datum = getattr(alt.datum, self._field)
        if self._aggregation_id:
            agg_string = 'a={0:d}&'.format(self._aggregation_id)
        else:
            agg_string = ''
        url = '{0:s}?{1:s}q={2:s}:"'.format(
            self._sketch_url, agg_string, self._field)
        return chart.transform_calculate(
            url=url + datum + '" ' + self._extra_query_url) 
开发者ID:google,项目名称:timesketch,代码行数:25,代码来源:interface.py

示例8: generate_chart

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def generate_chart(self):
        """Returns an altair Vega-lite chart."""
        if not self.chart_type:
            raise TypeError('Unable to generate chart, missing a chart type.')

        if not self._parameters.get('supported_charts'):
            self._parameters['supported_charts'] = self.chart_type

        data = self.lazyload_data()
        meta = data.get('meta', {})
        vega_spec = meta.get('vega_spec')

        if not vega_spec:
            return altair.Chart(pandas.DataFrame()).mark_point()

        vega_spec_string = json.dumps(vega_spec)
        return altair.Chart.from_json(vega_spec_string) 
开发者ID:google,项目名称:timesketch,代码行数:19,代码来源:aggregation.py

示例9: to_chart

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def to_chart(G, pos):
    """Construct a single Altair Chart for
    """
    # Build node layer
    node_df = to_pandas_nodes(G, pos)
    node_layer = alt.Chart(node_df)

    # Build edge layer
    edge_df = to_pandas_edges(G, pos)
    edge_layer = alt.Chart(edge_df)

    # Layer chart
    chart = alt.LayerChart(
        layer=(edge_layer, node_layer)
    )
    chart = despine(chart)
    return chart 
开发者ID:Zsailer,项目名称:nx_altair,代码行数:19,代码来源:core.py

示例10: scatterplot

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def scatterplot(x, y, data, hue=None, xlim=None, ylim=None):
    # TODO: refactor so it uses category_chart_kwargs?
    if xlim is None:
        xlim = get_limit_tuple(data[x])
    if ylim is None:
        ylim = get_limit_tuple(data[y])
    xscale = alt.Scale(domain=xlim)
    yscale = alt.Scale(domain=ylim)
    
    other_args = {'color': '{hue}:N'.format(hue=hue)} if hue else {}
    points = alt.Chart(data).mark_circle().encode(
        alt.X(x, scale=xscale),
        alt.Y(y, scale=yscale),
        **other_args
    )
    return points 
开发者ID:PythonCharmers,项目名称:starborn,代码行数:18,代码来源:core.py

示例11: stripplot

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def stripplot(x=None, y=None, hue=None, data=None):
    # TODO: refactor so it uses category_chart_kwargs()
    if data is None:
        if y is None:
            data = x.to_frame()
            x = data.columns[0]
        elif x is None:
            data = y.to_frame()
            y = data.columns[0]
        else:
            raise RuntimeError('not supported yet ...')

    kwargs = {}
    if x is not None:
        kwargs['x'] = '{x}'.format(x=x)
    if y is not None:
        kwargs['y'] = '{y}'.format(y=y)
    if hue is not None:
        kwargs['color'] = hue

    chart = alt.Chart(data).mark_tick().encode(**kwargs)
    return chart 
开发者ID:PythonCharmers,项目名称:starborn,代码行数:24,代码来源:core.py

示例12: pairplot

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def pairplot(data, hue=None, vars=None):
    if vars is None:
        vars = list(data.columns)

    chart = alt.Chart(data).mark_circle().encode(
                alt.X(alt.repeat("column"), type='quantitative'),
                alt.Y(alt.repeat("row"), type='quantitative'),
                color='{hue}:N'.format(hue=hue)
            ).properties(
                width=250,
                height=250
            ).repeat(
                row=vars,
                column=vars
            )
    return chart 
开发者ID:PythonCharmers,项目名称:starborn,代码行数:18,代码来源:core.py

示例13: violinplot

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def violinplot(x=None, y=None, data=None, orient=None):
    # TODO: automatically infer orientation

    if orient is None or orient == 'v':
        kwargs = dict(
                    x=alt.X('count(*):Q',
                            axis=alt.Axis(grid=False, labels=False),
                            stack='center',
                            title=''),
                    y=alt.Y('{y}:Q'.format(y=y), bin=alt.Bin(maxbins=100)),
                    column='{x}:N'.format(x=x),
                    color='{x}:N'.format(x=x)
        )
    else:
        kwargs = dict(
                    y=alt.Y('count(*):Q',
                            axis=alt.Axis(grid=False, labels=False),
                            stack='center',
                            title=''),
                    x=alt.X('{x}:Q'.format(x=x), bin=alt.Bin(maxbins=100)),
                    row='{y}:N'.format(y=y),
                    color='{y}:N'.format(y=y)
        )
    chart = alt.Chart(data).mark_area().encode(**kwargs)
    return chart 
开发者ID:PythonCharmers,项目名称:starborn,代码行数:27,代码来源:core.py

示例14: hist

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def hist(self, bins=None, orientation="vertical", **kwargs):
        data = self._preprocess_data(with_index=False)
        column = data.columns[0]
        if isinstance(bins, int):
            bins = alt.Bin(maxbins=bins)
        elif bins is None:
            bins = True
        if orientation == "vertical":
            Indep, Dep = alt.X, alt.Y
        elif orientation == "horizontal":
            Indep, Dep = alt.Y, alt.X
        else:
            raise ValueError("orientation must be 'horizontal' or 'vertical'.")

        mark = self._get_mark_def({"type": "bar", "orient": orientation}, kwargs)
        return alt.Chart(data, mark=mark).encode(
            Indep(column, title=None, bin=bins), Dep("count()", title="Frequency")
        ) 
开发者ID:altair-viz,项目名称:altair_pandas,代码行数:20,代码来源:_core.py

示例15: _plot

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Chart [as 别名]
def _plot(self, data=None, width=450, height=300, title=None, figsize=None, dpi=75):
        if data is None:
            data = self._data

        if title is None:
            title = ""

        if figsize is not None:
            width_inches, height_inches = figsize
            width = 0.8 * dpi * width_inches
            height = 0.8 * dpi * height_inches

        chart = alt.Chart(data=data).properties(width=width, height=height, title=title)
        return chart 
开发者ID:altair-viz,项目名称:pdvega,代码行数:16,代码来源:_core.py


注:本文中的altair.Chart方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。