本文整理汇总了Python中altair.Color方法的典型用法代码示例。如果您正苦于以下问题:Python altair.Color方法的具体用法?Python altair.Color怎么用?Python altair.Color使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类altair
的用法示例。
在下文中一共展示了altair.Color方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: visualize
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [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),
)
示例2: altair_cluster_tsne
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [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
示例3: generate
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [as 别名]
def generate(self):
"""Generate the chart.
Returns:
Instance of altair.Chart
"""
chart = self._get_chart_with_transform()
self._add_url_href(self.encoding)
if self.chart_title:
chart = chart.mark_circle(filled=True, size=100).properties(
title=self.chart_title)
else:
chart = chart.mark_circle(filled=True, size=100)
field = self.encoding.get('y', {}).get('field', 'count')
color = alt.Color(field=field, type='quantitative')
chart.encoding = alt.FacetedEncoding.from_dict(self.encoding)
chart.encoding.color = color
return chart
示例4: altair_step_matrix
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [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
示例5: st_heatmap
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [as 别名]
def st_heatmap(
heatmap_df: pd.DataFrame, x_col_name: str, y_col_name: str, color_col_name: str
):
heatmap = (
alt.Chart(heatmap_df, height=700, width=700)
.mark_rect()
.encode(alt.X(x_col_name), alt.Y(y_col_name), alt.Color(color_col_name))
)
st.altair_chart(heatmap)
示例6: airline_chart
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [as 别名]
def airline_chart(
source: alt.Chart, subset: List[str], name: str, loess=True
) -> alt.Chart:
chart = source.transform_filter(
alt.FieldOneOfPredicate(field="airline", oneOf=subset)
)
highlight = alt.selection(
type="single", nearest=True, on="mouseover", fields=["airline"]
)
points = (
chart.mark_point()
.encode(
x="day",
y=alt.Y("rate", title="# of flights (normalized)"),
color=alt.Color("airline", legend=alt.Legend(title=name)),
tooltip=["day", "airline", "count"],
opacity=alt.value(0.3),
)
.add_selection(highlight)
)
lines = chart.mark_line().encode(
x="day",
y="rate",
color="airline",
size=alt.condition(~highlight, alt.value(1), alt.value(3)),
)
if loess:
lines = lines.transform_loess(
"day", "rate", groupby=["airline"], bandwidth=0.2
)
return lines + points
示例7: airport_chart
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [as 别名]
def airport_chart(source: alt.Chart, subset: List[str], name: str) -> alt.Chart:
chart = source.transform_filter(
alt.FieldOneOfPredicate(field="airport", oneOf=subset)
)
highlight = alt.selection(
type="single", nearest=True, on="mouseover", fields=["airport"]
)
points = (
chart.mark_point()
.encode(
x="day",
y=alt.Y("count", title="# of departing flights"),
color=alt.Color("airport", legend=alt.Legend(title=name)),
tooltip=["day", "airport", "city", "count"],
opacity=alt.value(0.3),
)
.add_selection(highlight)
)
lines = (
chart.mark_line()
.encode(
x="day",
y="count",
color="airport",
size=alt.condition(~highlight, alt.value(1), alt.value(3)),
)
.transform_loess("day", "count", groupby=["airport"], bandwidth=0.2)
)
return lines + points
示例8: jointplot
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [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)
示例9: _xy
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [as 别名]
def _xy(self, mark, x=None, y=None, stacked=False, subplots=False, **kwargs):
data = self._preprocess_data(with_index=True)
if x is None:
x = data.columns[0]
else:
x = _valid_column(x)
assert x in data.columns
if y is None:
y_values = list(data.columns[1:])
else:
y = _valid_column(y)
assert y in data.columns
y_values = [y]
chart = (
alt.Chart(data, mark=self._get_mark_def(mark, kwargs))
.transform_fold(y_values, as_=["column", "value"])
.encode(
x=x,
y=alt.Y("value:Q", title=None, stack=stacked),
color=alt.Color("column:N", title=None),
tooltip=[x] + y_values,
)
.interactive()
)
if subplots:
nrows, ncols = _get_layout(len(y_values), kwargs.get("layout", (-1, 1)))
chart = chart.encode(facet=alt.Facet("column:N", title=None)).properties(
columns=ncols
)
return chart
示例10: show_label_distribution
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [as 别名]
def show_label_distribution(
sample_labels: Union[List[str], List[List[str]]],
all_labels: Optional[Union[List[str], List[List[str]]]] = None,
):
if sample_labels is not None:
st.header("Label Distribution")
label_counts = _collect_label_counts(sample_labels)
if all_labels is None:
label_chart = (
alt.Chart(label_counts, height=500, width=700)
.mark_bar()
.encode(
alt.X("Label", type="nominal"),
alt.Y("Proportion", type="quantitative"),
)
)
else:
label_counts["Label Set"] = "Sample"
all_label_counts = _collect_label_counts(all_labels)
all_label_counts["Label Set"] = "All Documents"
label_counts = pd.concat([label_counts, all_label_counts])
label_chart = (
alt.Chart(label_counts, width=100)
.mark_bar()
.encode(
alt.X(
"Label Set",
type="nominal",
title=None,
sort=["Sample", "All Documents"],
),
alt.Y("Proportion", type="quantitative"),
alt.Column(
"Label", type="nominal", header=alt.Header(labelAngle=0)
),
alt.Color("Label Set", type="nominal", legend=None),
)
)
st.altair_chart(label_chart)
示例11: visualize_models
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [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
示例12: visualize_models
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [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
示例13: scatter_matrix
# 需要导入模块: import altair [as 别名]
# 或者: from altair import Color [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()