Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
rng = np.random.RandomState(1)
x = rng.rand(40) ** 2
y = 10 - 1. / (x + 0.1) + rng.randn(40)
df = pd.DataFrame({'x': x, 'y': y})
# Define the degree of the polynomial fit
degree_list = [1, 3, 5]
# Build a dataframe with the fitted data
poly_data = pd.DataFrame({'xfit': np.linspace(df['x'].min(), df['x'].max(), 500)})
for degree in degree_list:
poly_data[str(degree)] = np.poly1d(np.polyfit(df['x'], df['y'], degree))(poly_data['xfit'])
# Plot the data points on an interactive axis
points = alt.Chart(df).mark_circle(color='black').encode(
x=alt.X('x', title='x'),
y=alt.Y('y', title='y')
).interactive()
# Plot the best fit polynomials
polynomial_fit = alt.Chart(poly_data).transform_fold(
['1', '3', '5'],
as_=['degree', 'yfit']
).mark_line().encode(
x='xfit:Q',
y='yfit:Q',
color='degree:N'
)
points + polynomial_fit
).transform_calculate(
year="year(datum.Date)"
).transform_calculate(
decade="floor(datum.year / 10)"
).transform_calculate(
scaled_date="(datum.year % 10) + (month(datum.Date)/12)"
).transform_window(
first_date='first_value(scaled_date)',
last_date='last_value(scaled_date)',
sort=[{"field": "scaled_date", "order": "ascending"}],
groupby=['decade'],
frame=[None, None]
).transform_calculate(
end="datum.first_date === datum.scaled_date ? 'first' : datum.last_date === datum.scaled_date ? 'last' : null"
).encode(
x=alt.X(
"scaled_date:Q",
axis=alt.Axis(title="Year into Decade", tickCount=11)
),
y=alt.Y(
"CO2:Q",
title="CO2 concentration in ppm",
scale=alt.Scale(zero=False)
)
)
line = base.mark_line().encode(
color=alt.Color(
"decade:O",
scale=alt.Scale(scheme="magma"),
legend=None
)
def filtered_hist(field, label, filter):
"""Creates a layered chart of histograms.
The first layer (light gray) contains the histogram of the full data, and the
second contains the histogram of the filtered data.
Args:
field: the field for which to generate the histogram.
label: String label of the histogram.
filter: an alt.Selection object to be used to filter the data.
"""
base = alt.Chart().mark_bar().encode(
x=alt.X(field, bin=alt.Bin(maxbins=10), title=label),
y="count()",
).properties(
width=300,
)
return alt.layer(
base.transform_filter(filter),
base.encode(color=alt.value('lightgray'), opacity=alt.value(.7)),
).resolve_scale(y='independent')
interval
)
#TODO get best score not mock https://altair-viz.github.io/user_guide/transform.html
bottom_charts = alt.layer(
base_bottom,
highlight_bottom,
best_score,
data=data
).repeat(
column=param_cols,
)
metric_line = alt.Chart(data, width=width).mark_area(filled=False).encode(
y=alt.Y("{}:Q".format(metric_col),bin=alt.Bin(maxbins=metric_bins), title=None),
x=alt.X('count()', title=metric_col),
color=alt.Color('mean({}):Q'.format(metric_col), scale=alt.Scale(scheme='yelloworangered'), legend=None),
).add_selection(
interval
)
metric_bar = alt.Chart(data, width=width).mark_bar().encode(
y=alt.Y("{}:Q".format(metric_col),bin=alt.Bin(maxbins=metric_bins), title=None),
x=alt.X('count()', title=metric_col),
color=alt.Color('mean({}):Q'.format(metric_col), scale=alt.Scale(scheme='yelloworangered'), legend=None),
)
metric_chart = alt.layer(metric_bar, metric_line)
combined_chart = alt.vconcat(top_charts,
alt.hconcat(bottom_charts, metric_chart))
return combined_chart
Natural Disasters
-----------------
This example shows a visualization of global deaths from natural disasters.
"""
# category: case studies
import altair as alt
from vega_datasets import data
source = data.disasters.url
alt.Chart(source).mark_circle(
opacity=0.8,
stroke='black',
strokeWidth=1
).encode(
alt.X('Year:O', axis=alt.Axis(labelAngle=0)),
alt.Y('Entity:N'),
alt.Size('Deaths:Q',
scale=alt.Scale(range=[0, 4000]),
legend=alt.Legend(title='Annual Global Deaths')
),
alt.Color('Entity:N', legend=None)
).properties(
width=450,
height=320
).transform_filter(
alt.datum.Entity != 'All natural disasters'
)
"""
Layered Plot with Dual-Axis
---------------------------
This example shows how to combine two plots and keep their axes.
"""
# category: bar charts
import altair as alt
from vega_datasets import data
source = data.seattle_weather()
base = alt.Chart(source).encode(
alt.X('month(date):O',
axis=alt.Axis(format='%b'),
scale=alt.Scale(zero=False)
)
)
bar = base.mark_bar().encode(
y='mean(precipitation)'
)
line = base.mark_line(color='red').encode(
y='mean(temp_max)',
)
alt.layer(
bar,
"""
Binned Heatmap
--------------
This example shows how to make a heatmap from binned quantitative data.
"""
# category: other charts
import altair as alt
from vega_datasets import data
source = data.movies()
alt.Chart(source).mark_rect().encode(
alt.X('IMDB_Rating:Q', bin=alt.Bin(maxbins=60)),
alt.Y('Rotten_Tomatoes_Rating:Q', bin=alt.Bin(maxbins=40)),
alt.Color('count(IMDB_Rating):Q', scale=alt.Scale(scheme='greenblue'))
)
"""
Horizontal Grouped Bar Chart
----------------------------
This example shows a grouped bar chart achieved by making cosmetic changes to a trellis plot.
"""
# category: bar charts
import altair as alt
from vega_datasets import data
source = data.barley()
alt.Chart(source).mark_bar().encode(
# The field used to define the subelements of each group
x=alt.X(
'year:N',
axis=alt.Axis(title="")
),
# The length of the bars
y=alt.Y(
'yield:Q',
axis=alt.Axis(grid=False)
),
color='year:N',
# The field used to group the subelements
column='variety:N'
).configure_view(
stroke='transparent' # Remove the trellis frames so multiple charts appear as one.
).transform_filter(
alt.datum.site == 'Morris'
)
def _build_depth_histogram(data):
"""Build histogram with depth (DP)."""
width = 200
height = 200
title = 'Depth'
depth_data = _integer_counts_to_histogram(data)
depth_histogram = _placeholder_for_empty_chart(
'No entries in VCF with DP', width=width, height=height, title=title)
if not depth_data.empty:
# s = bin_start, e = bin_end, c = count
depth_histogram = alt.Chart(depth_data).mark_bar(color=BAR_COLOR_DEPTH) \
.encode(x=alt.X('s', title='Depth'),
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 depth_histogram