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


Python altair.Scale方法代码示例

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


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

示例1: visualize

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Scale [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 Scale [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: _get_plot_command

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Scale [as 别名]
def _get_plot_command(e):
    """ Given a function, data type and data column name,
    find the plot command

    >>> e = {'encoding': 'x', 'field': 'petalWidth', 'scale': 'log'}
    >>> r = _get_plot_command(e)
    >>> assert r.to_dict() == {'field': 'petalWidth', 'scale': {'type': 'log'}}
    """
    d = {k: v for k, v in e.items()}
    if "field" not in e:
        return

    encoding = d.pop("encoding")
    column = d.pop("field")

    scale = {}
    if any([key in d for key in ["scale", "zero"]]):
        scale = {
            "scale": altair.Scale(type=d.pop("scale", None), zero=d.pop("zero", None))
        }

    d.update(scale)
    return getattr(altair, encoding.capitalize())(column, **d) 
开发者ID:altair-viz,项目名称:altair_widgets,代码行数:25,代码来源:widget.py

示例4: scatterplot

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Scale [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

示例5: frame_selector_ui

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Scale [as 别名]
def frame_selector_ui(summary):
    st.sidebar.markdown("# Frame")

    # The user can pick which type of object to search for.
    object_type = st.sidebar.selectbox("Search for which objects?", summary.columns, 2)

    # The user can select a range for how many of the selected objecgt should be present.
    min_elts, max_elts = st.sidebar.slider("How many %ss (select a range)?" % object_type, 0, 25, [10, 20])
    selected_frames = get_selected_frames(summary, object_type, min_elts, max_elts)
    if len(selected_frames) < 1:
        return None, None

    # Choose a frame out of the selected frames.
    selected_frame_index = st.sidebar.slider("Choose a frame (index)", 0, len(selected_frames) - 1, 0)

    # Draw an altair chart in the sidebar with information on the frame.
    objects_per_frame = summary.loc[selected_frames, object_type].reset_index(drop=True).reset_index()
    chart = alt.Chart(objects_per_frame, height=120).mark_area().encode(
        alt.X("index:Q", scale=alt.Scale(nice=False)),
        alt.Y("%s:Q" % object_type))
    selected_frame_df = pd.DataFrame({"selected_frame": [selected_frame_index]})
    vline = alt.Chart(selected_frame_df).mark_rule(color="red").encode(
        alt.X("selected_frame:Q", axis=None)
    )
    st.sidebar.altair_chart(alt.layer(chart, vline))

    selected_frame = selected_frames[selected_frame_index]
    return selected_frame_index, selected_frame

# Select frames based on the selection in the sidebar 
开发者ID:streamlit,项目名称:demo-self-driving,代码行数:32,代码来源:app.py

示例6: altair_step_matrix

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Scale [as 别名]
def altair_step_matrix(diff, plot_name=None, title='', vmin=None, vmax=None, font_size=12, **kwargs):
    heatmap_data = diff.reset_index().melt('index')
    heatmap_data.columns = ['y', 'x', 'z']
    table = alt.Chart(heatmap_data).encode(
        x=alt.X('x:O', sort=None),
        y=alt.Y('y:O', sort=None)
    )
    heatmap = table.mark_rect().encode(
        color=alt.Color(
            'z:Q',
            scale=alt.Scale(scheme='blues'),
        )
    )
    text = table.mark_text(
        align='center', fontSize=font_size
    ).encode(
        text='z',
        color=alt.condition(
            abs(alt.datum.z) < 0.8,
            alt.value('black'),
            alt.value('white'))
    )
    heatmap_object = (heatmap + text).properties(
        width=3 * font_size * len(diff.columns),
        height=2 * font_size * diff.shape[0]
    )
    return heatmap_object, plot_name, None, diff.retention.retention_config 
开发者ID:retentioneering,项目名称:retentioneering-tools,代码行数:29,代码来源:plot.py

示例7: jointplot

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Scale [as 别名]
def jointplot(x, y, data, kind='scatter', hue=None, xlim=None, ylim=None):
    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)
 
    points = scatterplot(x, y, data, hue=hue, xlim=xlim, ylim=ylim)

    area_args = {'opacity': .3, 'interpolate': 'step'}

    blank_axis = alt.Axis(title='')

    top_hist = alt.Chart(data).mark_area(**area_args).encode(
        alt.X('{x}:Q'.format(x=x),
              # when using bins, the axis scale is set through
              # the bin extent, so we do not specify the scale here
              # (which would be ignored anyway)
              bin=alt.Bin(maxbins=20, extent=xscale.domain),
              stack=None,
              axis=blank_axis,
             ),
        alt.Y('count()', stack=None, axis=blank_axis),
        alt.Color('{hue}:N'.format(hue=hue)),
    ).properties(height=60)

    right_hist = alt.Chart(data).mark_area(**area_args).encode(
        alt.Y('{y}:Q'.format(y=y),
              bin=alt.Bin(maxbins=20, extent=yscale.domain),
              stack=None,
              axis=blank_axis,
             ),
        alt.X('count()', stack=None, axis=blank_axis),
        alt.Color('{hue}:N'.format(hue=hue)),
    ).properties(width=60)

    return top_hist & (points | right_hist) 
开发者ID:PythonCharmers,项目名称:starborn,代码行数:40,代码来源:core.py

示例8: heatmap

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Scale [as 别名]
def heatmap(data, vmin=None, vmax=None, annot=None, fmt='.2g'):

    # We always want to have a DataFrame with semantic information
    if not isinstance(data, pd.DataFrame):
        matrix = np.asarray(data)
        data = pd.DataFrame(matrix)

    melted = data.stack().reset_index(name='Value')

    x = data.columns.name
    y = data.index.name

    heatmap = alt.Chart(melted).mark_rect().encode(
        alt.X('{x}:O'.format(x=x), scale=alt.Scale(paddingInner=0)),
        alt.Y('{y}:O'.format(y=y), scale=alt.Scale(paddingInner=0)),
        color='Value:Q'
    )
    
    if not annot:
        return heatmap

    # Overlay text
    text = alt.Chart(melted).mark_text(baseline='middle').encode(
        x='{x}:O'.format(x=x),
        y='{y}:O'.format(y=y),
        text=alt.Text('Value', format=fmt),
        color=alt.condition(alt.expr.datum['Value'] > 70,
                            alt.value('black'),
                            alt.value('white'))
    )
    return heatmap + text 
开发者ID:PythonCharmers,项目名称:starborn,代码行数:33,代码来源:core.py

示例9: visualize_models

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Scale [as 别名]
def visualize_models(self, 
        instance_hash: Dict[InstanceKey, Instance]={},
        instance_hash_rewritten: Dict[InstanceKey, Instance]={},
        filtered_instances: List[InstanceKey]=None,
        models: List[str]=[]):
        """
        Visualize the group distribution. 
        It's a one-bar histogram that displays the count of instances in the group, and
        the proportion of incorrect predictions.
        Because of the incorrect prediction proportion, this historgram is different
        for each different model. 
        
        Parameters
        ----------
        instance_hash : Dict[InstanceKey, Instance]
            A dict that saves all the *original* instances, by default {}. 
            It denotes by the corresponding instance keys.
            If ``{}``, resolve to ``Instance.instance_hash``.
        instance_hash_rewritten : Dict[InstanceKey, Instance]
            A dict that saves all the *rewritten* instances, by default {}. 
            It denotes by the corresponding instance keys.
            If ``{}``, resolve to ``Instance.instance_hash_rewritten``.
        filtered_instances : List[InstanceKey], optional
            A selected list of instances. If given, only display the distribution
            of the selected instances, by default None
        models : List[str], optional
            A list of instances, with the bars for each group concated vertically.
            By default []. If [], resolve to ``[ Instance.model ]``.
        
        Returns
        -------
        alt.Chart
            An altair chart object. 
        """
        instance_hash = instance_hash or Instance.instance_hash
        instance_hash_rewritten = instance_hash_rewritten or Instance.instance_hash_rewritten
        models = models or [ Instance.resolve_default_model(None) ]
        output = []
        for model in models:
            #Instance.set_default_model(model=model)
            data = self.serialize(instance_hash, instance_hash_rewritten, filtered_instances, model)
            for correctness, count in data["counts"].items():
                output.append({
                    "correctness": correctness,
                    "count": count,
                    "model": model
                })
        
        df = pd.DataFrame(output)
        chart = alt.Chart(df).mark_bar().encode(
            y=alt.Y('model:N'),
            x=alt.X('count:Q', stack="zero"),
            color=alt.Color('correctness:N', scale=alt.Scale(domain=["correct", "incorrect"])),
            tooltip=['model:N', 'count:Q', 'correctness:N']
        ).properties(width=100)#.configure_facet(spacing=5)#
        return chart 
开发者ID:uwdata,项目名称:errudite,代码行数:58,代码来源:group.py

示例10: visualize_models

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Scale [as 别名]
def visualize_models(self, 
        instance_hash: Dict[InstanceKey, Instance]={},
        instance_hash_rewritten: Dict[InstanceKey, Instance]={},
        filtered_instances: List[InstanceKey]=None,
        models: str=[]):
        """
        Visualize the rewrite distribution. 
        It's a one-bar histogram that displays the count of instances rewritten, and
        the proportion of "flip_to_correct", "flip_to_incorrect", "unflip"
        Because of the flipping proportion, this historgram is different
        for each different model. 
        
        Parameters
        ----------
        instance_hash : Dict[InstanceKey, Instance]
            A dict that saves all the *original* instances, by default {}. 
            It denotes by the corresponding instance keys.
            If ``{}``, resolve to ``Instance.instance_hash``.
        instance_hash_rewritten : Dict[InstanceKey, Instance]
            A dict that saves all the *rewritten* instances, by default {}. 
            It denotes by the corresponding instance keys.
            If ``{}``, resolve to ``Instance.instance_hash_rewritten``.
        filtered_instances : List[InstanceKey], optional
            A selected list of instances. If given, only display the distribution
            of the selected instances, by default None
        models : List[str], optional
            A list of instances, with the bars for each group concated vertically.
            By default []. If [], resolve to ``[ Instance.model ]``.
        
        Returns
        -------
        alt.Chart
            An altair chart object. 
        """
        model = models or [ Instance.model ]
        instance_hash = instance_hash or Instance.instance_hash
        instance_hash_rewritten = instance_hash_rewritten or Instance.instance_hash_rewritten
        if not models:
            models = [ Instance.resolve_default_model(None) ]
        output = []
        for model in models:
            #Instance.set_default_model(model=model)
            data = self.serialize(instance_hash, instance_hash_rewritten, filtered_instances, model)
            for flip, count in data["counts"].items():
                output.append({
                    "flip": flip,
                    "count": count,
                    "model": model
                })
        df = pd.DataFrame(output)
        chart = alt.Chart(df).mark_bar().encode(
            y=alt.Y('model:N'),
            x=alt.X('count:Q', stack="zero"),
            color=alt.Color('flip:N', scale=alt.Scale(
                range=["#1f77b4", "#ff7f0e", "#c7c7c7"],
                domain=["flip_to_correct", "flip_to_incorrect", "unflip"])),
            tooltip=['model:N', 'count:Q', 'correctness:N']
        ).properties(width=100)#.configure_facet(spacing=5)#
        return chart 
开发者ID:uwdata,项目名称:errudite,代码行数:61,代码来源:rewrite.py

示例11: scatter_matrix

# 需要导入模块: import altair [as 别名]
# 或者: from altair import Scale [as 别名]
def scatter_matrix(
    df,
    color: Union[str, None] = None,
    alpha: float = 1.0,
    tooltip: Union[List[str], tooltipList, None] = None,
    **kwargs
) -> alt.Chart:
    """ plots a scatter matrix

    At the moment does not support neither histogram nor kde;
    Uses f-f scatterplots instead. Interactive and with a cusotmizable
    tooltip

    Parameters
    ----------
    df : DataFame
        DataFame to be used for scatterplot. Only numeric columns will be included.
    color : string [optional]
        Can be a column name or specific color value (hex, webcolors).
    alpha : float
        Opacity of the markers, within [0,1]
    tooltip: list [optional]
        List of specific column names or alt.Tooltip objects. If none (default),
        will show all columns.
    """
    dfc = _preprocess_data(df)
    tooltip = _process_tooltip(tooltip) or dfc.columns.tolist()
    cols = dfc._get_numeric_data().columns.tolist()

    chart = (
        alt.Chart(dfc)
        .mark_circle()
        .encode(
            x=alt.X(alt.repeat("column"), type="quantitative"),
            y=alt.X(alt.repeat("row"), type="quantitative"),
            opacity=alt.value(alpha),
            tooltip=tooltip,
        )
        .properties(width=150, height=150)
    )

    if color:
        color = str(color)

        if color in dfc:
            color = alt.Color(color)
            if "colormap" in kwargs:
                color.scale = alt.Scale(scheme=kwargs.get("colormap"))
        else:
            color = alt.value(color)
        chart = chart.encode(color=color)

    return chart.repeat(row=cols, column=cols).interactive() 
开发者ID:altair-viz,项目名称:altair_pandas,代码行数:55,代码来源:_misc.py


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