Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
size=alt.Size('sum(workshop_hours):Q', legend=None),
tooltip=['workshop_name:O', 'class_size:Q']
).transform_filter(
multi
).add_selection(
brush
)
picker = alt.Chart(df).mark_rect().encode(
y=alt.Y('name:N'),
color=color,
).add_selection(
multi
)
a = alt.Chart(resp_nwm).mark_square(size=40).encode(
x=alt.X('variable:N', scale=alt.Scale(rangeStep=80), axis=alt.Axis(labelAngle=0)),
y=alt.Y('value'),
color=alt.Color('name', legend=None),
tooltip=['name','value']
).transform_calculate(
value=expr.round(expr.exp(datum.value))
).transform_filter(
multi
)
b = a.mark_line(opacity=0.8, interpolate='monotone').encode(
x=alt.X('variable')
)
chart = picker | (point & a+b) | (box & bar)
#chart = alt.hconcat(picker, alt.vconcat(point, a+b) , alt.vconcat(box, bar))
return chart.to_json()
for a in spec.annotation]
else:
annotation = [None] * len(spec.mz)
color = [colors[None]] * len(spec.mz)
calc_mz = [a.calc_mz if a is not None else None for a in annotation]
fragment = [str(a) if a is not None else None for a in annotation]
spec_df = pd.DataFrame({'exp_mz': spec.mz, 'intensity': intensity,
'calc_mz': calc_mz, 'fragment': fragment,
'color': color})
x_axis = altair.X('exp_mz', axis=altair.Axis(title='m/z',
titleFontStyle='italic',
grid=grid),
scale=altair.Scale(nice=True, padding=5, zero=False))
y_axis = altair.Y('intensity',
axis=altair.Axis(title='Intensity', format='%',
grid=grid),
scale=altair.Scale(nice=True, padding=5))
color = altair.Color('color', scale=None, legend=None)
tooltip_not_annotated = [altair.Tooltip('exp_mz', format='.4f',
title='Experimental m/z'),
altair.Tooltip('intensity', format='.0%',
title='Intensity')]
tooltip_annotated = [altair.Tooltip('fragment', title='Fragment'),
altair.Tooltip('exp_mz', format='.4f',
title='Experimental m/z'),
altair.Tooltip('calc_mz', format='.4f',
title='Theoretical m/z'),
altair.Tooltip('intensity', format='.0%',
title='Intensity')]
# Unannotated peaks.
spec_plot = (altair.Chart(spec_df[spec_df['fragment'].isna()])
height = 200
ti = titv_counts['Transition']
tv = titv_counts['Transversion']
# Show TiTv ratio with fallback to avoid division by 0
titv_ratio = '%.2f' % (float(ti) / tv) if tv > 0 else '%d / 0' % (ti)
title = 'Biallelic Ti/Tv ratio: %s' % (titv_ratio)
tt_chart = _placeholder_for_empty_chart(
'No biallelic SNPs', width=width, height=height, title=title)
tt_labels = ['Transition', 'Transversion']
if sum([titv_counts[k] for k in titv_counts]) > 0:
tt_data = _dict_to_dataframe(titv_counts)
bars = alt.Chart(tt_data).mark_bar().encode(
x=alt.X(
'label', sort=tt_labels, axis=alt.Axis(title=None, labelAngle=0)),
y=alt.Y('value', axis=alt.Axis(title='Count', format='s')),
tooltip=alt.Tooltip('value', format='.4s'),
color=alt.Color(
'label',
legend=None,
sort=tt_labels,
scale=alt.Scale(scheme='teals', domain=tt_labels)))
labels = bars.mark_text(dy=-5).encode(text=alt.Text('value', format='.4s'))
tt_chart = (bars + labels).properties(
title=title, width=width, height=height)
return tt_chart
============================
This chart visualizes the age distribution of the US population over time,
using a wrapped faceting of the data by decade.
"""
# category: case studies
import altair as alt
from vega_datasets import data
source = data.population.url
alt.Chart(source).mark_area().encode(
x='age:O',
y=alt.Y(
'sum(people):Q',
title='Population',
axis=alt.Axis(format='~s')
),
facet=alt.Facet('year:O', columns=5),
).properties(
title='US Age Distribution By Year',
width=90,
height=80
)
pca_vals = pd.DataFrame(pca_vals, index=df.index)
pca_vals.rename(columns=lambda x: "PC{}".format(x + 1), inplace=True)
# label the axes
if xlabel is None:
xlabel = "PC1 ({}%)".format(round(pca.explained_variance_ratio_[0] * 100, 2))
if ylabel is None:
ylabel = "PC2 ({}%)".format(round(pca.explained_variance_ratio_[1] * 100, 2))
# don't send all the data to vega, just what we're plotting
plot_data = pd.concat(
[pca_vals.loc[:, ("PC1", "PC2")], magic_metadata], axis=1
).reset_index()
alt_kwargs = dict(
x=alt.X("PC1", axis=alt.Axis(title=xlabel)),
y=alt.Y("PC2", axis=alt.Axis(title=ylabel)),
tooltip=[magic_fields[t] for t in tooltip],
href="url:N",
url="https://app.onecodex.com/classification/" + alt.datum.classification_id,
)
# only add these parameters if they are in use
if color:
domain = magic_metadata[color].values
color_kwargs = {
"legend": alt.Legend(title=magic_fields[color]),
}
if not is_continuous(domain):
color_range = interleave_palette(domain)
color_kwargs["scale"] = alt.Scale(domain=domain, range=color_range)
This example demonstrates how to generate a facetted scatterplot,
with marginal facetted histograms, and how to share their respective
- x,some y-limits.
"""
# category: other charts
import altair as alt
from vega_datasets import data
iris = data.iris()
xscale = alt.Scale(domain=(4.0, 8.0))
yscale = alt.Scale(domain=(1.9, 4.55))
area_args = {'opacity': .3, 'interpolate': 'step'}
blank_axis = alt.Axis(title='')
points = alt.Chart(iris).mark_circle().encode(
alt.X('sepalLength', scale=xscale),
alt.Y('sepalWidth', scale=yscale),
color='species',
)
top_hist = alt.Chart(iris).mark_area(**area_args).encode(
alt.X('sepalLength:Q',
# 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,
),
# gq = genotype quality, found at :GQ: in FORMAT column of VCF
width = 200
height = 200
title = 'Genotype quality'
gq_data = _integer_counts_to_histogram(data)
gq_histogram = _placeholder_for_empty_chart(
'No entries in VCF with GQ', width=width, height=height, title=title)
if not gq_data.empty:
# standardize x-axis limits across reports
domain = [min(0, data[0][0]), max(150, data[-1][0])]
# s = bin_start, e = bin_end, c = count
gq_histogram = alt.Chart(gq_data).mark_bar(color=BAR_COLOR_GQ) \
.encode(
x=alt.X('s', title='GQ', scale=alt.Scale(domain=domain)),
x2='e',
y=alt.Y('c', title='Count', stack=True, axis=alt.Axis(format='s'))) \
.properties(width=width, height=height, title=title) \
.interactive(bind_y=False)
return gq_histogram
from vega_datasets import data
alt.Chart(data.cars()).transform_density(
'Miles_per_Gallon',
as_=['Miles_per_Gallon', 'density'],
extent=[5, 50],
groupby=['Origin']
).mark_area(orient='horizontal').encode(
y='Miles_per_Gallon:Q',
color='Origin:N',
x=alt.X(
'density:Q',
stack='center',
impute=None,
title=None,
axis=alt.Axis(labels=False, values=[0],grid=False, ticks=True),
),
column=alt.Column(
'Origin:N',
header=alt.Header(
titleOrient='bottom',
labelOrient='bottom',
labelPadding=0,
),
)
).properties(
width=100
).configure_facet(
spacing=0
).configure_view(
stroke=None
)
.transform_window(
sort=[alt.SortField(field=default_rank_col, order="ascending")],
# We don't use an alt.WindowFieldDef here because python gets
# confused when you use "as" as an actual argument name. So we just
# use this syntax.
window=[{"op": "row_number", "as": "qurro_x"}],
)
.encode(
# type="ordinal" needed on the scale here to make bars adjacent;
# see https://stackoverflow.com/a/55544817/10730311.
x=alt.X(
"qurro_x",
title="Feature Rankings",
type="ordinal",
scale=alt.Scale(paddingOuter=1, paddingInner=0, rangeStep=1),
axis=alt.Axis(ticks=False, labelAngle=0),
),
y=alt.Y(default_rank_col, type="quantitative"),
color=alt.Color(
"qurro_classification",
title="Log-Ratio Classification",
scale=alt.Scale(
domain=["None", "Numerator", "Denominator", "Both"],
range=["#e0e0e0", "#f00", "#00f", "#949"],
),
),
tooltip=[
alt.Tooltip(
field="qurro_x",
title="Current Ranking",
type="quantitative",
),
"""
Grouped Bar Chart
-----------------------
This example shows a population broken out by gender and age for a specific year.
The grouping is achieved by building a trellis plot with narrow column
encoded on the age groups and x-axes encoded on gender.
"""
# category: bar charts
import altair as alt
from vega_datasets import data
source = data.population.url
alt.Chart(source).mark_bar(stroke='transparent').encode(
alt.X('gender:N', scale=alt.Scale(rangeStep=12), axis=alt.Axis(title='')),
alt.Y('sum(people):Q', axis=alt.Axis(title='population', grid=False)),
color=alt.Color('gender:N', scale=alt.Scale(range=["#EA98D2", "#659CCA"])),
column='age:O'
).configure_view(
stroke='transparent'
).configure_axis(
domainWidth=0.8
).transform_filter(
alt.datum.year == 2000
).transform_calculate(
'gender', alt.expr.if_(alt.datum.sex == 2, 'Female', 'Male')
)