Skip to content

Instantly share code, notes, and snippets.

@sidravi1
Last active August 28, 2018 14:16
Show Gist options
  • Save sidravi1/a4f1cff1b681d0a74fe278fc5bfd3a2f to your computer and use it in GitHub Desktop.
Save sidravi1/a4f1cff1b681d0a74fe278fc5bfd3a2f to your computer and use it in GitHub Desktop.
Altair filtered histogram greater than selection
## Altair chart for Rafa
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import altair as alt
import seaborn as sns
from matplotlib import colors
# Create data
np.random.seed(102)
data = pd.DataFrame({'value_':np.random.random(size=(1000)), 'cat': np.tile(np.arange(1, 11),100)})
# Create 'greater than n-1' dataset
all_df = []
for i in data['cat'].unique():
vals = data.loc[data.cat > i, 'value_'].values
df = pd.DataFrame({'gt_vals':vals, 'n':np.full_like(vals, i)})
all_df.append(df)
master_df = pd.concat(all_df)
# Choose colors
colors2 = sns.color_palette(n_colors=10)
# Create altair chart
selector = alt.selection(type='single', fields=['n'])
top = alt.Chart(master_df).mark_rect(strokeWidth=2, stroke='white', fill=colors.rgb2hex(colors2[0])).encode(
x = alt.X('gt_vals:Q',title="Values", bin=alt.Bin(step=(edges[1] - edges[0]), extent=[0, 1], nice=False)),
y = alt.Y("count()"),
).transform_filter(
selector
).properties(
width=400
)
bottom = alt.Chart(master_df).mark_rect().encode(
x = alt.X("n:O", axis=None),
color=alt.condition(selector, alt.Color("n:N", legend=None), alt.value('lightgray'))
).add_selection(
selector
).properties(
width=400
)
text = alt.Chart(master_df).mark_text().encode(
x = alt.X("n:O", title="Categories", axis = alt.Axis(labels = False, ticks=False)),
text = alt.Text("n:O", ),
color=alt.value('white')
).properties(
width=400,
height=40
)
top & (bottom + text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment