def barplot( x=None, y=None, hue=None, data=None, estimator=np.mean, ci=95, size=None, aspect=1, orient=None, color=None, palette=None, saturation=.75, dodge=True ): xs, ys = "x", "y" orient = infer_orient(data[x], data[y], orient) if orient == "h": x, y = y, x xs, ys = ys, xs estimator = _validate_estimator(estimator, ci) encodings = _bar_encodings(x, y, xs, ys, hue, dodge, estimator) chart = alt.Chart(data).mark_bar().encode(**encodings) if ci: ci_encodings = _bar_ci_encodings(x, y, xs, ys, hue, dodge, estimator) ci_layer = alt.Chart().mark_rule().encode(**ci_encodings) chart.data = alt.Undefined chart = alt.LayerChart(data=data, layer=[chart, ci_layer]) if hue and dodge: facet_dir = "column" if orient == "v" else "row" chart = chart.facet(**{facet_dir: "%s:N" % x}) size_chart(chart, size, aspect) pal = vega_palette(palette, color, saturation) return chart.configure_range(category=pal)
def pointplot( x=None, y=None, hue=None, data=None, estimator=np.mean, ci=95, join=True, size=None, aspect=1, orient=None, color=None, palette=None, saturation=.75 ): xs, ys = "x", "y" orient = infer_orient(data[x], data[y], orient) if orient == "h": x, y = y, x xs, ys = ys, xs estimator = _validate_estimator(estimator, ci) encodings = _point_encodings(x, y, xs, ys, hue, estimator) chart = alt.Chart(data).mark_circle().encode(**encodings) layers = [chart] if join: layers.append(alt.Chart().mark_line().encode(**encodings)) if ci: ci_encodings = _point_ci_encodings(x, y, xs, ys, hue, estimator) cfield = hue if hue else "___" ci_encodings["color"] = alt.Color(field=cfield, type="nominal", legend=None) layers.append(alt.Chart().mark_rule().encode(**ci_encodings)) if len(layers) > 1: chart.data = alt.Undefined chart = alt.LayerChart(data=data, layer=layers) size_chart(chart, size, aspect) pal = vega_palette(palette, color, saturation) return chart.configure_range(category=pal)
def graphPayouts(sim): #Make a version of this with pops aggRecord = sim["aggRecord"][['LPayoff', 'HPayoff']].copy() meltedAgg = aggRecord.assign(round= aggRecord.index).melt(id_vars="round") display(alt.LayerChart(meltedAgg).encode( x='round', y='value:Q', color='variable:N' ).add_layers( alt.Chart().mark_point(), alt.Chart().mark_line() ))
def graphPayoutsJustGraph(sim): #Make a version of this with pops aggRecord = sim["aggRecord"][['LPayoff', 'HPayoff']].copy() meltedAgg = aggRecord.assign(round= aggRecord.index).melt(id_vars="round") return alt.LayerChart(meltedAgg).encode( x='round', y='value:Q', color=alt.Color('variable:N', legend=alt.Legend(title="Payout", orient="left")) ).add_layers( alt.Chart().mark_point(), alt.Chart().mark_line() ).properties( width=700, height = 180)
def to_chart(G, pos): """Construct a single Altair Chart for """ # Build node layer node_df = to_pandas_nodes(G, pos) node_layer = alt.Chart(node_df) # Build edge layer edge_df = to_pandas_edges(G, pos) edge_layer = alt.Chart(edge_df) # Layer chart chart = alt.LayerChart(layer=(edge_layer, node_layer)) chart = despine(chart) return chart
def plotStrategyWealthOverTime(sim): simRecord = sim["balanceRecord"].copy() simRecord["Strategy"] = sim["finalScores"]["Strategy"] wideScores = (simRecord .groupby("Strategy")[simRecord.columns[:-1]] .mean() .transpose() .assign(round= range(101)) .melt(id_vars="round")) display(alt.LayerChart(wideScores).encode( x='round', y='value:Q', color=alt.Color('Strategy:N', legend=alt.Legend(title="Payout", orient="left")) ).add_layers( alt.Chart().mark_point(), alt.Chart().mark_line() ).properties( width=700, height = 180))
def daily(): # data ldn = pd.read_csv('../data/output/ml_general.csv')[::-1][35:] ldn = ldn.rename(columns={'London': 'new', 'London_7': 'avg'}) # getting date and new cases today = pd.to_datetime(ldn.iloc[-1].date).strftime('%b %d') cases = int(ldn.iloc[-1].new) # avg line avg = alt.Chart(ldn).mark_line(strokeWidth=2.5, color='#27516B').encode(x='date:T', y='avg:Q') # daily feather new = alt.Chart(ldn).mark_line(opacity=0.35, strokeDash=[1, 1]).encode( x='date:T', y=alt.Y('new:Q', scale=alt.Scale(domain=[0, int(ldn.new.max())]))) # final datum dot dot = alt.Chart(ldn).mark_circle(size=5, opacity=0.8).encode( x='date:T', y=alt.Y('new:Q', scale=alt.Scale(domain=[0, int(ldn.new.max())]))) # combined d = alt.LayerChart(layer=[new, avg, dot]).properties( width=375, height=375 # title = { # 'text': '15 new cases', # 'subtitle': 'new cases with 7-day average' # } ) return d, today, cases
""" Multiple Marks ============== This example demonstrates creating a single chart with multiple markers representing the same data. """ import altair as alt from vega_datasets import data stocks = data.stocks() alt.LayerChart(stocks).encode(x='date:T', y='price:Q', color='symbol:N').add_layers( alt.Chart().mark_point(), alt.Chart().mark_line())
""" Ranged Dot Plot ----------------- This example shows a ranged dot plot that uses 'layer' to convey changing life expectancy for the five most populous countries (between 1955 and 2000). """ import altair as alt from vega_datasets import data chart = alt.LayerChart(data=data.countries.url).transform_filter( filter={ "field": 'country', "oneOf": ["China", "India", "United States", "Indonesia", "Brazil"] }).transform_filter(filter={ 'field': 'year', "oneOf": [1955, 2000] }) chart += alt.Chart().mark_line(color='#db646f').encode(x='life_expect:Q', y='country:N', detail='country:N') # Add points for life expectancy in 1955 & 2000 chart += alt.Chart().mark_point(size=100, opacity=1, filled=True).encode( x='life_expect:Q', y='country:N', color=alt.Color('year:O', scale=alt.Scale(domain=['1955', '2000'], range=['#e6959c', '#911a24']))).interactive()
def create_scatter(self, name='chart.html'): """ :param name: str name of the output file """ case_a = self.case_a case_b = self.case_b # add regression layer, True by default regression_layer = self.chart + self.chart.transform_regression( case_a, case_b).mark_line(color='black') # nearest will popup data of the nearest point nearest = alt.selection(type='single', nearest=True, on='mouseover', fields=['x'], empty='none') text = alt.Chart(self.corona_df).mark_text( align='left', baseline='middle', color='black', dy=-9, dx=-7, fontSize=15, ).encode(text='text_popup', tooltip=[alt.Tooltip('location:N', title='Country')] + [ alt.Tooltip(case_a, type='quantitative', title=case_a), alt.Tooltip(case_b, type='quantitative', title=case_b) ], x=f'{case_a}:Q', y=f'{case_b}:Q').add_selection(nearest) text_layer = self.chart + text line = self.chart + alt.Chart(self.corona_df).mark_rule( color='red', strokeWidth=2).encode(y='medianY:Q') + alt.Chart( self.corona_df).mark_rule(color='red', strokeWidth=2).encode(x='medianX:Q') # add layers to the map layers = [line, regression_layer, text_layer] chart = alt.LayerChart(self.corona_df, layers) chart = chart.add_selection(self.selection).transform_filter( self.selection ).properties( width=490, height=395, padding=40 # interactive to add interaction to the plot # Cant work on Android ).interactive() # save here dir = 'corona_full/templates/charts/' location = dir + name # renderer svg is a bit faster chart.save(location, embed_options={'renderer': 'svg'}) # update created HTML page new_style = ''' <script> const msPerDay = 24 * 60 * 60 * 1000; const date = new Date('December 31, 2019').getTime() function toDateTime(x) { // transform ms to date let new_date = new Date(x * msPerDay + date); return new_date.toLocaleDateString(); } function Init () { // Launch in start - attach event to the only input var target = document.getElementsByTagName("input")[0]; if (target.addEventListener) { target.addEventListener("input", updateTextInput, false); } else if (target.attachEvent) { target.attachEvent("oninout", updateTextInput); } else { target["oninput"] = updateTextInput; } } function getTexts() { let g_el = document.getElementsByClassName('mark-text role-mark layer_2_layer_1_marks')[0] let iso_code = parent.document.getElementsByName('iso_code'); let checked = [] for (let i = 0; i<iso_code.length;i++) { if (iso_code[i].checked) {checked.push(iso_code[i].value)} } var texts = g_el.getElementsByTagName('text'); return [texts, checked] } function clearIso() { a = getTexts() let texts = a[0] let checked = a[1] for (let i=0; i<texts.length; i++) { if (checked.includes(texts[i].innerHTML)) { texts[i].style.display = 'block' } else { texts[i].style.display = 'none' } } } async function updateTextInput(val) { // Show date of showed data on page // base day is 31.12.2019 var x = document.getElementsByClassName("vega-bind-name")[0] val = document.getElementsByTagName("input")[0].value val = toDateTime(val); x.innerHTML = val; //console.log('UpdateTextInput', getTexts()[0][0], getTexts()[0][0].style) await sleep(1) clearIso() } window.onload = function() { // Hide iso codes text: needed by default clearIso() Init(); // attach some buttons var divv = document.createElement("div"); // next day a= createfn('+', plus) // auto scroll b = createfn('auto', changeAuto) // prev day c = createfn('-', minus) divv.appendChild(c); divv.appendChild(b); divv.appendChild(a); divv.classList.add('button-div'); document.getElementsByTagName('body')[0].appendChild(divv); // let inputElement = document.getElementsByTagName("input")[0] // attach one more event to input, clearIso() on change // inputElement.addEventListener("input", clearIso, false); // inputElement.addEventListener("change", clearIso, false); } function plus(){ let inputElement = document.getElementsByTagName("input")[0] inputElement.value++; inputElement.dispatchEvent(new Event('input')) // await sleep(.01) // clearIso(); } function minus(){ let inputElement = document.getElementsByTagName("input")[0] inputElement.value--; inputElement.dispatchEvent(new Event('input')) } function sleep(ms) { return new Promise( resolve => setTimeout(resolve, ms) ); } run = false async function changeAuto() { // change showed day run = !run var ele = document.getElementsByTagName('input')[0]; if (ele.value === ele.max && run) { ele.value = 0; } do { plus(); // wait half sec await sleep(499); } while (run); } function createfn(sign, operation){ // create a button with a function on click var element = document.createElement("button"); var para = document.createTextNode(sign); element.appendChild(para); element.addEventListener("click", operation, false); return element } </script> <style> input { width: 95%; } span { display: none; } span[class] { display: inline; } .vega-bind-name { visibility: visible; } .vega-bind { text-align: center; paddin-left: 2%; padding-right: 3%; } .button-div { display: table; margin-right: auto; margin-left: auto; } ''' # NO ENDING STYLE TAG !!! with open(location, 'r', encoding='utf-8') as fr: data = fr.read() current_day = max(self.corona_df_full['date']) data = data.replace('<style>', new_style).replace('Date:', current_day) # write new styles and JS to the sasme document with open(location, 'w', encoding='utf-8') as fw: fw.write(data)
def __init__(self): self.chart = alt.LayerChart()
def regplot( x, y, data=None, x_estimator=None, x_bins=None, x_ci="ci", x_range=None, y_range=None, truncate=False, scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, order=1, logistic=False, lowess=False, robust=False, logx=False, color=None, scatter_kws={}, line_kws={}, ax=None, palette=None, height=None, aspect=1, color_scale=None ): if data is None: data, names = build_dataframe({"x": x, "y": y}) x, y = names["x"], names["y"] if x_range is None: x_raw_range = (data[x].min(), data[x].max()) x_pad = 0.05*(x_raw_range[1] - x_raw_range[0]) x_range = (x_raw_range[0] - x_pad, x_raw_range[1] + x_pad) def plot_regression(data, color): p = sns.regression._RegressionPlotter( data[x], data[y], x_estimator=x_estimator, x_bins=x_bins, x_ci=x_ci, n_boot=n_boot, units=units, ci=ci, truncate=truncate, order=order, logistic=logistic, lowess=lowess, robust=robust, logx=logx ) layers = [] grid, yhat, err_bands = p.fit_regression(x_range=x_range) layers.append(plot(grid, yhat, color=color, **line_kws)) if err_bands is not None: area = fill_between(grid, *err_bands, color=color) area.encoding.opacity = alt.value(0.15) layers.append(area) return layers def plot_scatter(data, color): p = sns.regression._RegressionPlotter( data[x], data[y], x_estimator=x_estimator, x_bins=x_bins, x_ci=x_ci, n_boot=n_boot, units=units, ci=ci, truncate=truncate, order=order, logistic=logistic, lowess=lowess, robust=robust, logx=logx ) layers = [] if p.x_estimator is None: layers.append(pscatter(x, y, data=data, color=color, **scatter_kws)) else: xs, ys, cis = p.estimate_data if [ci for ci in cis if ci is not None]: for xval, cci in zip(xs, cis): ci_df = pd.DataFrame({x: [xval, xval], y: cci}) layers.append(plot(x, y, data=ci_df)) estimate_df = pd.DataFrame({x: xs, y: ys}) layers.append(pscatter(x, y, data=estimate_df, color=color, **scatter_kws)) return layers if color and color in list(data.columns): if color_scale is None: val = data[color].unique() pal = sns.color_palette(palette) color_scale = alt.Scale(domain=list(val), range=vega_palette(pal)) else: val = color_scale.domain color_map = {} for i in range(len(color_scale.domain)): color_map[color_scale.domain[i]] = color_scale.range[i % len(color_scale.range)] layers = [] if scatter: for v in data[color].unique(): part = data.loc[data[color] == v] layers += plot_scatter(part, color_map[v]) if fit_reg: for v in data[color].unique(): part = data.loc[data[color] == v] layers += plot_regression(part, color_map[v]) else: layers = [] if scatter: layers += plot_scatter(data, color) if fit_reg: layers += plot_regression(data, color) for layer in layers: if isinstance(layer.mark, six.string_types): layer.mark = dict(type=layer.mark, clip=True) else: layer.mark.clip = True layer.encoding.x.scale=alt.Scale(domain=x_range, nice=False) if y_range is not None: layer.encoding.y.scale=alt.Scale(domain=y_range, nice=False) layer.config = alt.Undefined chart = alt.LayerChart(layer=layers) return chart
def Plots(result, nth, w, h): # This allows for data greater than 5000 rows to be plotted alt.data_transformers.disable_max_rows() x, y17, y17w, y17b, y18, y40, y40b = (result[4], result[5], result[6], result[7], result[8], result[9], result[10]) TPDsi, TPDei, Arsi, Arei = (result[14], result[15], result[16], result[17]) wf, watstart, watend, ratio1718 = (result[18], result[11], result[12], result[13]) temp = list(x[TPDsi:TPDei]) temp = temp - temp[0] temp = 323 + temp * 10 temp = list(temp[0::nth]) # cut out and keep every nth point # Raw data Cuts xr = list(x[0::nth]) y17r = list(y17[0::nth]) y18r = list(y18[0::nth]) y40r = list(y40[0::nth]) # TPDsi:TPDei cuts xt = (list(x[TPDsi:TPDei]))[0::nth] y17t = (list(y17[TPDsi:TPDei]))[0::nth] y17wt = (list(y17w[TPDsi:TPDei]))[0::nth] y17bt = (list(y17b[TPDsi:TPDei]))[0::nth] y18t = (list(y18[TPDsi:TPDei]))[0::nth] # Ar cuts xa = (list(x[Arsi:Arei]))[0::nth] y40a = (list(y40[Arsi:Arei]))[0::nth] y40ba = (list(y40b[Arsi:Arei]))[0::nth] raw_data = pd.DataFrame({'x': xr, 'y17': y17r, 'y18': y18r, 'y40': y40r}) raw_reshape = pd.melt(raw_data, id_vars=['x'], value_vars=['y17', 'y18', 'y40'], var_name='legend', value_name='y') raw_chart = alt.Chart(raw_reshape).mark_line(size=3).encode( alt.X('x', axis=alt.Axis(tickCount=7, title='Time (min)')), alt.Y('y', axis=alt.Axis(tickCount=7, title='Intensity (counts)')), alt.Color('legend', legend=alt.Legend( orient='top-left'))).configure_axis(grid=False).properties( width=w, height=h, title='Raw Data from CSV').interactive() TPD_data = pd.DataFrame({ 'x': xt, 'y17': y17t, 'y17 water corrected': y17wt, 'y17 baseline corrected': y17bt, 'y18': y18t }) TPD_reshape = pd.melt(TPD_data, id_vars=['x'], value_vars=[ 'y17', 'y17 water corrected', 'y17 baseline corrected', 'y18' ], var_name='legend', value_name='y') TPD_chart = alt.Chart(TPD_reshape).mark_line(size=3).encode( alt.X('x', axis=alt.Axis(title='Time (min)')), alt.Y('y', axis=alt.Axis(title='Intensity (counts)')), alt.Color('legend', legend=alt.Legend( orient='top-right'))).configure_axis(grid=False).properties( width=w, height=h, title='TPD: y17 Water and Baseline Correction ') Ar_data = pd.DataFrame({ 'x': xa, 'y40': y40a, 'y40 baseline corrected': y40ba }) Ar_reshape = pd.melt(Ar_data, id_vars=['x'], value_vars=['y40', 'y40 baseline corrected'], var_name='legend', value_name='y') Ar_chart = alt.Chart(Ar_reshape).mark_line(size=3).encode( alt.X('x', axis=alt.Axis(title='Time (min)')), alt.Y('y', axis=alt.Axis(title='Intensity (counts)')), alt.Color('legend', legend=alt.Legend(orient='top-right'))).configure_axis( grid=False).properties(width=w, height=h, title='Ar Pulse') T_data = pd.DataFrame({'T': temp, 'y': y17bt}) T_chart = alt.Chart(T_data).mark_line(size=3).encode( alt.X('T', axis=alt.Axis(title='Temp (K)')), alt.Y('y', axis=alt.Axis(title='Intensity (counts)')), ).configure_axis(grid=False).properties( width=w, height=h, title='TPD as a Function of Temperature') if wf == 1: W_data = pd.DataFrame({'x': x[watstart:watend], 'y': ratio1718}) W_chart = alt.Chart(W_data).mark_line(size=3).encode( alt.X('x', axis=alt.Axis(title='Time (min)')), alt.Y('y', axis=alt.Axis(title='Value of y17/y18 Preceeding TPD')), ).configure_axis(grid=False).properties( width=w, height=h, title='Water Correction Factor') else: W_chart = alt.LayerChart() return (raw_chart, TPD_chart, Ar_chart, T_chart, W_chart)
def create_graph(): # retira o número máximo de linhas para pot com Altair alt.data_transformers.disable_max_rows() # faz query no banco de dados autores = queryDB('author', ['ID_author','author']) artigos = queryDB('paper', ['ID_paper','paper']) author_paper = queryDB('author_paper', ['ID_paper','ID_author']) autores['ID_author'] = autores['ID_author'].astype(str) artigos['ID_paper'] = artigos['ID_paper'].astype(str) ### renderiza os gráficos ## Grafo 1 - Autores (authors) print('Preparando grafo dos autores...') graph = nx.Graph() # dataframe com colunas: paper e [lista_autores] group = pd.DataFrame(author_paper.groupby('ID_paper')['ID_author'].apply(list)) # Adicionando "edges" for j,row in group.iterrows(): i=len(row['ID_author']) for i in range(len(row['ID_author'])): for k in range(i,len(row['ID_author'])): graph.add_edge(row['ID_author'][i], row['ID_author'][k]) pos = nx.spring_layout(graph,k=0.2, iterations=50, weight=0.1, center=(0.5,0.5)) # forces graph layout # coletando nodes nodes = to_pandas_nodes(graph,pos) nodes.reset_index(inplace=True) nodes.rename(columns={'index':'ID_author'}, inplace=True) nodes = pd.merge(nodes,autores,on='ID_author') # coletando nome dos autores nodes = pd.merge(nodes,author_paper, on='ID_author') # coletando ID_paper # coletando edges edges = to_pandas_edges(graph,pos) # Gráfico 1 print('Criando interatividade com o Altair (autores) ...') selector = alt.selection_single(empty='all',fields=['ID_author']) # iniciando seletor points = alt.Chart(nodes).add_selection(selector).mark_point(filled=True,size=90).encode( alt.X('x', axis=alt.Axis(title='')), alt.Y('y', axis=alt.Axis(title='')), tooltip='author', opacity=alt.condition(selector,alt.value(0.95),alt.value(0.4),legend=None), color=alt.condition(selector, 'ID_author', alt.value('lightgray'), legend=None) ).properties( selection=selector ).transform_filter(selector) # cria um background para efeitos de transição do seletor bk = alt.Chart(nodes).mark_point(color='lightgray',filled=True,size=90).encode( alt.X('x', axis=alt.Axis(title='')), alt.Y('y', axis=alt.Axis(title='')), tooltip='author', opacity=alt.value(0.4), ) lines = alt.Chart(edges).mark_line(color='salmon').encode( alt.X('x', axis=alt.Axis(title='')), alt.Y('y', axis=alt.Axis(title='')), detail='edge', opacity=alt.value(0.15) ) chart = alt.LayerChart(layer=(lines,bk+points)).properties( height=350, width=450 ).interactive() ## Grafo 2 - Artigos (papers) print('Preparando grafo dos artigos...') graph1 = nx.Graph() group1 = pd.DataFrame(author_paper.groupby('ID_author')['ID_paper'].apply(list)) # Adicionando "edges" for j,row in group1.iterrows(): i=len(row['ID_paper']) for i in range(len(row['ID_paper'])): for k in range(i,len(row['ID_paper'])): graph1.add_edge(row['ID_paper'][i], row['ID_paper'][k]) pos1 = nx.spring_layout(graph1,k=0.2, iterations=50, weight=0.1, center=(0.5,0.5)) # forces graph layout # coletando nodes nodes1 = to_pandas_nodes(graph1, pos1) nodes1.reset_index(inplace=True) nodes1.rename(columns={'index':'ID_paper'}, inplace=True) nodes1 = pd.merge(nodes1,artigos,on='ID_paper') # coletando nome dos papers nodes1 = pd.merge(nodes1,author_paper,on='ID_paper') # coletando ID_author # coletando edges edges1 = to_pandas_edges(graph1,pos1) # Gráfico 2 print('Criando interatividade com o Altair (artigos)...') points1 = alt.Chart(nodes1).add_selection(selector).mark_point(filled=True,size=90).encode( alt.X('x', axis=alt.Axis(title='')), alt.Y('y', axis=alt.Axis(title='')), tooltip='paper', opacity=alt.condition(selector,alt.value(0.95),alt.value(0.4),legend=None), color=alt.condition(selector, 'ID_author', alt.value('lightgray'), legend=None) ).transform_filter(selector) # cria um background para efeitos de transição do seletor bk1 = alt.Chart(nodes1).mark_point(color='lightgray',filled=True,size=90).encode( alt.X('x', axis=alt.Axis(title='')), alt.Y('y', axis=alt.Axis(title='')), tooltip='paper', opacity=alt.value(0.4), ) lines1 = alt.Chart(edges1).mark_line(color='lightblue').encode( alt.X('x', axis=alt.Axis(title='')), alt.Y('y', axis=alt.Axis(title='')), detail='edge', opacity=alt.value(0.2) ) chart1 = alt.LayerChart(layer=(lines1,bk1 + points1)).properties( height=350, width=450 ).interactive() ### Concatenando horizontamnete os gráficos 1 e 2 horiz_chart = alt.hconcat(chart, chart1 ).configure_axis( ticks=False, grid=False, domain=False, labels=False).configure_view( strokeWidth=0 ) return horiz_chart.to_json()
start_date = cases.Date.iloc[0].replace(tzinfo=None) end_date = cases.Date.iloc[-1].replace(tzinfo=None) #st.markdown("### Please choose the range of dates") dates = st.date_input("Please choose the range of dates", [start_date, end_date], start_date, end_date) if len(dates) < 2: start_date = dates[0] else: start_date, end_date = dates cases = cases[(cases.Date >= pd.Timestamp(start_date, tz="Europe/Paris")) & (cases.Date < pd.Timestamp(end_date + dt.timedelta(days=1), tz="Europe/Paris"))] chart = alt.LayerChart() #st.markdown("### Evolution of Covid-19 cases for the chosen postal codes") tooltip = [ 'Date', alt.Tooltip('Week_of_year', title='Week of year'), 'Name', 'District', 'Population', alt.Tooltip('Area', title='Area (km²)', format='0.3'), alt.Tooltip(plot_y_axis_column_range, title='Range'), alt.Tooltip('NewDeaths_in_district_in_week', title='Weekly deaths in district') ] #,alt.Tooltip(plot_y_axis_column_min, title='Min', format='0.3'), x_axis = alt.X('Date', axis=alt.Axis(labels=True, format='%d %b')) y_axis = alt.Y(plot_y_axis_column_avg, title=plot_y_axis_title) legend = "|Area | Color | \n | - | - | \n" for i, plz_name in enumerate(chosen_postal_areas): color = colors[i]
def boxplot( x=None, y=None, hue=None, data=None, size=None, aspect=1, orient=None, color=None, palette=None, saturation=.75, dodge=True ): xs, ys = "x", "y" if data is None: data = pd.DataFrame({"x": x}) x = "x" if y: data["y"] = y y = "y" if x is None and y is None: # Make a box plot for each numeric column numeric_cols = [c for c in data if data[c].dtype in [np.float32, np.float64]] col = [] val = [] for c in numeric_cols: for v in data[c]: col.append(c) val.append(v) data = pd.DataFrame({"column": col, "value": val}) x = "column" y = "value" if orient == "h": x, y = y, x if y: orient = infer_orient(data[x], data[y], orient) elif orient is None: orient = "h" if orient == "h": x, y = y, x xs, ys = ys, xs xf = hue if hue and dodge else x # Main bar encodings = { ys: alt.Y(field=y, aggregate="q1", type="quantitative", axis={"title": y}), "%s2" % ys: alt.Y(field=y, aggregate="q3", type="quantitative"), "color": alt.Color(field=x ,type="nominal", legend=None), xs: alt.X(field=xf, type="nominal") } if x is None: del encodings["color"] del encodings[xs] if hue: legend = None if dodge else alt.Undefined encodings["color"] = alt.Color(field=hue ,type="nominal", legend=legend) bar_layer = alt.Chart().mark_bar().encode(**encodings) # Min/max range line range_encodings = { ys: alt.Y(field=y, aggregate="min", type="quantitative"), "%s2" % ys: alt.Y(field=y, aggregate="max", type="quantitative"), xs: alt.X(field=xf, type="nominal") } if x is None: del range_encodings[xs] range_layer = alt.Chart().mark_rule().encode(**range_encodings) # Median line median_encodings = { ys: alt.Y(field=y, aggregate="median", type="quantitative"), xs: alt.X(field=xf, type="nominal") } if x is None: del median_encodings[xs] median_layer = alt.Chart().mark_tick(size=18, color="black").encode(**median_encodings) chart = alt.LayerChart(data=data, layer=[range_layer, bar_layer, median_layer]) if hue and dodge: facet_dir = "column" if orient == "v" else "row" chart = chart.facet(**{facet_dir: "%s:N" % x}) size_chart(chart, size, aspect) pal = vega_palette(palette, color, saturation) return chart.configure_range(category=pal)