def returns_chart(report): # Time interval selector time_interval = alt.selection(type='interval', encodings=['x']) # Area plot areas = alt.Chart().mark_area(opacity=0.7).encode(x='index:T', y=alt.Y('accumulated return:Q', axis=alt.Axis(format='%'))) # Nearest point selector nearest = alt.selection(type='single', nearest=True, on='mouseover', fields=['index'], empty='none') points = areas.mark_point().encode(opacity=alt.condition(nearest, alt.value(1), alt.value(0))) # Transparent date selector selectors = alt.Chart().mark_point().encode( x='index:T', opacity=alt.value(0), ).add_selection(nearest) text = areas.mark_text( align='left', dx=5, dy=-5).encode(text=alt.condition(nearest, 'accumulated return:Q', alt.value(' '), format='.2%')) layered = alt.layer(selectors, points, text, areas.encode( alt.X('index:T', axis=alt.Axis(title='date'), scale=alt.Scale(domain=time_interval))), width=700, height=350, title='Returns over time') lower = areas.properties(width=700, height=70).add_selection(time_interval) return alt.vconcat(layered, lower, data=report.reset_index())
def get_names(names=["Robin", "Oliver"]): THIS_FOLDER = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(THIS_FOLDER, "./static/Personer.csv") df = pd.read_csv(filename, sep=";", encoding="ISO-8859-1") df = prepare_data(df, names) # Nerest selection nearest = alt.selection(type='single', nearest=True, on='mouseover', fields=['år'], empty='none') highlight = alt.selection(type='single', on='mouseover', fields=['name'], nearest=True) base = alt.Chart(df).encode(x='år:T', y='Antall:Q', color='name:N') points = base.mark_circle().encode( opacity=alt.value(0)).add_selection(highlight).properties(width=600) lines = base.mark_line().encode( size=alt.condition(~highlight, alt.value(1), alt.value(3))) fig = alt.layer(lines, points).properties(width=1200, height=700) return fig.to_json(indent=None)
def skyview_cmd(subsample, out_file, data_type='kepler'): brush = alt.selection( type='interval', resolve='global', on="[mousedown[event.shiftKey], window:mouseup] > \ window:mousemove!", zoom='False', translate="[mousedown[event.shiftKey], window:mouseup] > \ window:mousemove!") pan = alt.selection( type='interval', bind='scales', on="[mousedown[!event.shiftKey], window:mouseup] > \ window:mousemove!", translate="[mousedown[!event.shiftKey], window:mouseup] > \ window:mousemove!") if data_type == 'kepler': scale = alt.Scale(domain=['none', 'cand', 'conf'], range=['#4a69bd', '#e55039', '#f6b93b']) color = alt.Color('planet?:N', scale=scale) xscale = alt.Scale(domain=[270, 310]) yscale = alt.Scale(domain=[35, 55]) elif data_type == 'k2': #scale = alt.Scale(domain=['none', 'cand'], # range=['#4a69bd', '#e55039']) #color = alt.Color('k2c_disp:N', scale=scale) color = 'k2c_disp' xscale = alt.Scale(domain=[0, 360]) yscale = alt.Scale(domain=[-90, 90]) else: print("ERROR: data_type not recognized") return chart1 = alt.Chart(subsample).mark_point().encode( alt.X('ra_gaia', scale=xscale, axis=alt.Axis(title='Gaia RA (deg)')), alt.Y('dec_gaia', scale=yscale, axis=alt.Axis(title='Gaia Dec (deg)')), color=alt.condition(brush, color, alt.ColorValue('gray'))).properties( selection=brush + pan, projection={'type': 'gnomonic'}, width=450, height=500) chart2 = alt.Chart(subsample).mark_point().encode( alt.X('gaiamag_minus_kepmag', axis=alt.Axis(title='G - K (mag)')), alt.Y('abs_gmag', axis=alt.Axis(title='abs. G')), color=alt.condition(brush, color, alt.ColorValue('gray'))).properties( selection=brush, width=450, height=500) chart = chart1 | chart2 chart.savechart(out_file)
def plot_both(county="all counties", start=None, end=None): """ Gets a dataframe by calling __read_csv with the seelcted arguments. Creates a plot of cumulative cases over one y-axis and new cases over the other y-axis Args: county(str): Name of a county or all counties. Default value is all counties. start(str): Start date in the format "%d.%m.%Y". Default value is None and translates to first date in dataset. end(str): En date in the format "%d.%m.%Y". Default value is None and translates to first date in dataset. Returns: (Altair.Chart): A chart with the number of cases and cumulative number of cases plotted against the dates. """ cases = __read_csv(county, start, end) nearest_line = alt.selection(type="single", on="mouseover", fields=["Dato"], empty="none") nearest_bar = alt.selection(type="single", on="mouseover", fields=["Dato"], empty="none") base = (alt.Chart(cases).encode(alt.X("Dato", title="Date")).properties( title= f"Number of reported COVID-19 cases in {county} by specimen collection date" )) line = (base.mark_line(color="red").encode( alt.Y("Kumulativt antall", axis=alt.Axis(title="Cumulative number of cases")), tooltip=[ alt.Tooltip("Dato", title="Date"), alt.Tooltip("Kumulativt antall", title="Cumulative number of cases"), ], size=alt.condition(nearest_line, alt.value(5), alt.value(3)), ).add_selection(nearest_line)) bar = (base.mark_bar(size=n / len(cases) + 0.5).encode( alt.Y("Nye tilfeller", axis=alt.Axis(title="New cases")), tooltip=[ alt.Tooltip("Dato", title="Date"), alt.Tooltip("Nye tilfeller", title="New cases"), ], opacity=alt.condition(nearest_bar, alt.value(1), alt.value(0.7)), ).add_selection(nearest_bar)) layered = (alt.layer(line, bar).resolve_scale(y="independent").properties( width=600, height=500)) return layered
def mean_price_of_diesel_s10_over_time_by_region(df): df_product_diesels10 = df[df.Product == 'DIESEL S10'].reset_index( drop=True) highlight = alt.selection(type='single', on='mouseover', fields=['Macroregion'], nearest=True) k = alt.Chart( df_product_diesels10, title='Mean Price of Diesel S10 Over Time by Region').mark_line( ).encode(x='Year_Month', y='mean(Mean_Price)', color=alt.Color( 'Macroregion', legend=alt.Legend( title="Macroregion by color"))).properties(width=1000, height=400) points = k.mark_line().encode( opacity=alt.value(0)).add_selection(highlight).properties(width=600) lines = k.mark_line().encode( size=alt.condition(~highlight, alt.value(1), alt.value(3))) st.altair_chart(points + lines)
def get_map(self, day_str, title=""): chart_data = self._prepare_dataset(day_str) source = alt.topo_feature(data.world_110m.url, 'countries') background = alt.Chart(source).mark_geoshape( fill="lightgray", stroke="white").properties(width=1000, height=500).project("equirectangular") hover = alt.selection(type='single', on='mouseover', nearest=False, fields=[self.col_lat, self.col_long]) text = background.mark_text(dy=-5, align='right').encode( alt.Text(f'{self.col_name_countries}:N', type='nominal'), opacity=alt.condition(~hover, alt.value(0), alt.value(1))) points = alt.Chart(chart_data).mark_circle().encode( latitude=f"{self.col_lat}:Q", longitude=f"{self.col_long}:Q", size=alt.Size(f"{day_str}:Q", scale=alt.Scale(range=[0, 7000]), legend=None), order=alt.Order(f"{day_str}:Q", sort="descending"), tooltip=[f'{self.col_name_countries}:N', f'{day_str}:Q' ]).add_selection(hover).properties(title=title) chart = alt.layer(background, points, text) return chart
def plot_norway(): """ Makes a interactive geomap of norway with number of cases per 100k in every county. :return: the html file showing interactive geomap. """ data = pd.read_csv("resources/covid_rate_per_100000.csv", sep=';', index_col=False) county_list = data["Category"].to_list() insidens_list = [ float(i.replace(',', '.')) for i in data["Insidens"].to_list() ] data_as_dict = {"Category": county_list, "Insidens": insidens_list} df = pd.DataFrame.from_dict(data_as_dict) counties = alt.topo_feature( "https://raw.githubusercontent.com/deldersveld/topojson/master/countries/norway/norway-new-counties.json", "Fylker") nearest = alt.selection(type="single", on="mouseover", fields=["properties.navn"], empty="none") fig = alt.Chart(counties).mark_geoshape().encode( tooltip=[ alt.Tooltip("properties.navn:N", title="County"), alt.Tooltip("Insidens:Q", title="Cases per 100k capita"), ], color=alt.Color("Insidens:Q", scale=alt.Scale(scheme="reds"), legend=alt.Legend(title="Cases per 100k capita")), stroke=alt.condition(nearest, alt.value("gray"), alt.value(None)), opacity=alt.condition(nearest, alt.value(1), alt.value(0.8)), ).transform_lookup( lookup="properties.navn", from_=alt.LookupData(df, "Category", ["Insidens"])).properties( width=700, height=800, title="Number of cases per 100k in every county", ).add_selection(nearest) fig.save("templates/interactive_map.html") soup = BeautifulSoup(open("templates/interactive_map.html"), 'html.parser') head = soup.find('head') body = soup.find('body') script = soup.find('body').find('script') return render_template( "map.html", head=head, body=body, script=script, from_date=from_date, to_date=to_date, )
def users_and_queries_chart(self): df = self.users_and_queries_data() brush = alt.selection(type='interval', encodings=['y']) color = alt.condition(brush, alt.Color('count(Queries):Q'), alt.value('gray')) heat = alt.Chart(df).mark_rect().encode( x=alt.X("hours(Time):O", title='Time'), y=alt.Y("monthdate(Time):O", title='Number of queries'), color=color, tooltip=alt.Tooltip(['sum(Queries):Q', "hours(Time):O" ])).properties(height=350, width=700).add_selection(brush) line = alt.Chart(df).mark_bar().encode( x=alt.X('sender:N'), y=alt.Y('count():Q', scale=alt.Scale( domain=[0, 10]))).transform_filter(brush).properties( height=200, width=675) rule = alt.Chart(df).transform_joinaggregate( group_count='count(*)', groupby=['sender']).mark_rule(color='red').encode( y=alt.Y('mean(group_count):Q')).transform_filter(brush) red = alt.Chart(df).transform_joinaggregate( group_count='count(*)', groupby=['sender']).mark_rule(color='red').encode( y='mean(group_count):Q').transform_filter(brush) heatmap = alt.vconcat(heat, line + rule + red) return heatmap
def density_plot(data, stats, Season): """ creates a visualization of one square yard of seeded planting in plan view """ source = format_plotdata(data, stats, Season) if Season == 'Winter': pcolor = wcolor else: pcolor = color #interactive highlight function highlight = alt.selection(type='single', fields=['species', 'common_name'], empty="all") #define the density plot visualizeseeds = alt.Chart( data=source, title='Plan View of Proposed Planting').mark_point( filled=True, size=100).encode( x=alt.X('x', axis=alt.Axis(title='1 yard')), y=alt.Y('y', axis=alt.Axis(title='1 yard')), color=pcolor, shape=shape, tooltip=['species:N', 'common_name:N'], ).add_selection(highlight).properties( width=650, height=515).configure(background='#D3D3D3') return visualizeseeds
def generate_chart(df): if Config.is_continuous: base = alt.Chart(df).mark_line().encode(x="x", y="y", color="label") else: base = alt.Chart(df).mark_bar(opacity=0.2).encode( x="x:O", y=alt.Y('y', stack=None), color="label", ) nearest = alt.selection( type="single", nearest=True, on="mouseover", encodings=["x"], empty="none", ) selectors = alt.Chart(df).mark_point().encode( x=f'x:{"Q" if Config.is_continuous else "O"}', opacity=alt.value(0), ).add_selection(nearest) rules = alt.Chart(df).mark_rule(color='gray').encode( x=f'x:{"Q" if Config.is_continuous else "O"}', ).transform_filter( nearest) points = base.mark_point().encode( opacity=alt.condition(nearest, alt.value(1), alt.value(0))) text = base.mark_text(align='left', dx=5, dy=-5).encode(text=alt.condition( nearest, 'xy:N', alt.value(' '))).transform_calculate(xy=expr.join([ "(", expr.toString(expr.round(datum.x * 100) / 100), ', ', expr.toString(expr.round(datum.y * 100) / 100), ")" ], '')) chart = alt.layer(base, selectors, rules, points, text) return chart
def wickets_vs_season(player): wickets_vs_seasons = dr.wickets_in_season[dr.wickets_in_season['player'] == player] wickets_vs_seasons_base = alt.Chart(wickets_vs_seasons).encode( x='season:O', y='wickets:Q', tooltip=['player', 'wickets', 'matches'], ) highlight = alt.selection(type='multi', on='mouseover', fields=['season'], nearest=True) wickets_vs_season_points = wickets_vs_seasons_base.mark_circle().encode( opacity=alt.condition(~highlight, alt.value(0.7), alt.value(1)), size=alt.condition(~highlight, alt.value(70), alt.value(140)) ).add_selection( highlight, ).properties( height=300, width=900 ) wickets_vs_season_lines = wickets_vs_seasons_base.mark_line(point=True).encode( opacity=alt.condition(~highlight, alt.value(0.7), alt.value(0.7)), size=alt.condition(~highlight, alt.value(2), alt.value(2)) ) return (wickets_vs_season_points + wickets_vs_season_lines).configure_axis( grid=False ).configure_view( strokeOpacity=0 ).configure_axisBottom( labelAngle=0 )
def reproduction_rate_chart(data): chart_reproduction_rate = alt.Chart(data).mark_line( point=True, color='red').encode( alt.X("monthdate(day):O", title="Tag"), alt.Y("reproduction_rate:Q", title="Reproduktionsrate")) reproduction_nearest = alt.selection(type='single', nearest=True, on='mouseover', fields=['day'], empty='none') reproduction_selectors = alt.Chart(data).mark_point().encode( alt.X("monthdate(day)", title="Tag"), opacity=alt.value(0), ).add_selection(reproduction_nearest) reproduction_points = chart_reproduction_rate.mark_point().encode( opacity=alt.condition(reproduction_nearest, alt.value(1), alt.value( 0))) reproduction_text = chart_reproduction_rate.mark_text( align='left', dx=5, dy=5).encode(text=alt.condition( reproduction_nearest, 'reproduction_rate:Q', alt.value(' '))) rule = alt.Chart(data).mark_rule(color='gray').encode( alt.X("monthdate(day)", title="Tag"), ).transform_filter(reproduction_nearest) combinded_chart = alt.layer(chart_reproduction_rate, reproduction_selectors, reproduction_points, rule, reproduction_text).properties(width=1050, height=400) return to_json(combinded_chart)
def interactive_chart(df): nearest = alt.selection(type='single', nearest=True, on='mouseover', fields=['week'], empty='none') line = (alt.Chart(df).mark_line(interpolate='basis').encode( x='week', y='read', color='year:O')) selectors = (alt.Chart(df).mark_point().encode( x='week', opacity=alt.value(0)).add_selection(nearest)) points = (line.mark_point().encode( opacity=alt.condition(nearest, alt.value(1), alt.value(0)))) text = (line.mark_text( align='left', dx=5, dy=-5).encode(text=alt.condition(nearest, 'read', alt.value(' ')))) rules = (alt.Chart(df).mark_rule(color='red').encode( x='week').transform_filter(nearest)) chart = (alt.layer(line, selectors, points, rules, text).properties(width=500, height=300, background='white', title='goodreads Challenge')) return chart
def s_avg_graph(): df_solar_world = load_data_world_s() brush = alt.selection(type='interval', encodings=['x']) bars = alt.Chart().mark_bar().encode( alt.X('Year', scale=alt.Scale(zero=False)), y='mean(Solar_LCOE (2019 USD/kWh))', opacity=alt.condition(brush, alt.OpacityValue(1), alt.OpacityValue(0.7)), ).add_selection(brush).properties( title='Utility-scale solar PV weighted average cost of electricity', width=700, height=350) line = alt.Chart().mark_rule(color='firebrick').encode( y='mean(Solar_LCOE (2019 USD/kWh))', size=alt.SizeValue(3), tooltip=["mean(Solar_LCOE (2019 USD/kWh))"]).transform_filter(brush) country = st.selectbox("Select country", [ "Australia", "China", "France", "Germany", "India", "Italy", "Japan", "Netherlands", "Republic of Korea", "Spain", "Turkey", "Ukraine", "United Kingdom", "United States", "Vietnam" ]) xyz = alt.layer(bars, line, data=df_solar_world[df_solar_world["Country"] == country]) st.altair_chart(xyz)
def w_inst_graph(): df_wind_world = load_data_world_w() brush = alt.selection(type='interval', encodings=['x']) bars = alt.Chart().mark_bar().encode( alt.X('Year', scale=alt.Scale(zero=False)), y='mean(Total installed costs (2019 USD/kW))', opacity=alt.condition(brush, alt.OpacityValue(1), alt.OpacityValue(0.7)), ).add_selection(brush).properties( title='Utility-scale solar PV weighted average cost of electricity', width=700, height=350) line = alt.Chart().mark_rule(color='firebrick').encode( y='mean(Total installed costs (2019 USD/kW))', size=alt.SizeValue(3), tooltip=["mean(Total installed costs (2019 USD/kW))" ]).transform_filter(brush) country = st.selectbox("Select country", [ "Brazil", "Canada", "China", "Denmark", "France", "Germany", "India", "Italy", "Japan", "Mexico", "Spain", "Sweden", "Turkey", "United Kingdom", "United States" ]) xyz = alt.layer(bars, line, data=df_wind_world[df_wind_world["Country"] == country]) st.altair_chart(xyz)
def altair3(mydata): # basic line line = alt.Chart().mark_line().encode( x='date:T', y='totalPrice:Q', tooltip=[ alt.Tooltip('totalPrice:Q', title='Total Price (million)'), alt.Tooltip('date:T', timeUnit='yearmonth', title='Date') ]).properties(width=400) # add interactive line tooltips: https://altair-viz.github.io/gallery/multiline_tooltip.html # Create a selection that chooses the nearest point & selects based on x-value nearest = alt.selection(type='single', nearest=True, on='mouseover', fields=['date'], empty='none') # Transparent selectors across the chart. This is what tells us the x-value of the cursor selectors = alt.Chart().mark_point().encode( x='date:T', opacity=alt.value(0), ).add_selection(nearest) # Draw points on the line, and highlight based on selection points = line.mark_point().encode( opacity=alt.condition(nearest, alt.value(1), alt.value(0))) # Draw a rule at the location of the selection rules = alt.Chart().mark_rule(color='gray').encode( x='date:T', ).transform_filter(nearest) # Put the layers into a chart and bind the data line_totalprice = alt.layer(line, selectors, points, rules, data=mydata) return line_totalprice
def batsman_vs_season(player, season): batsman_vs_seasons = dr.batsman_runs[dr.batsman_runs['player'] == player][ dr.batsman_runs['season'] == int(season)] highlight = alt.selection(type='multi', on='mouseover', fields=['match'], nearest=True) batsman_vs_season_base = alt.Chart(batsman_vs_seasons).encode( x='match:O', y='runs:Q', tooltip=['player', 'runs', 'team', 'stadium'], ) batsman_vs_season_points = batsman_vs_season_base.mark_circle().encode( opacity=alt.condition(~highlight, alt.value(0.7), alt.value(1)), size=alt.condition(~highlight, alt.value(70), alt.value(140)) ).add_selection( highlight, ).properties( height=300, width=900 ) batsman_vs_season_lines = batsman_vs_season_base.mark_line(point=True).encode( opacity=alt.condition(~highlight, alt.value(0.7), alt.value(0.7)), size=alt.condition(~highlight, alt.value(2), alt.value(2)) ) return (batsman_vs_season_points + batsman_vs_season_lines).configure_axis( labels=False )
def selectionchart(self): """Chart with bottom time period selection Returns: [obj]: [altair chart object with time selection chart] """ brush = alt.selection(type='interval', encodings=['x']) upper = self.chart.encode( alt.X('date:T', scale=alt.Scale(domain=brush))) inline = self.draw.encode(alt.X(self.target, type='temporal', title=' ', axis=alt.Axis(grid=False)), alt.Y('y', type=self.type_, scale=alt.Scale(zero=False), title=' ', axis=alt.Axis(grid=False, labels=False)), alt.Color('показатель:N', ), opacity=alt.condition( self.leg, alt.value(1), alt.value(0.2))) lower = alt.layer(inline, self.rules).properties( width=self.width, height=20).add_selection(brush) return upper & lower
def ruled_altair_chart(source): line = alt.Chart(source).encode(x=alt.X('yearmonthdate(date):T', axis=alt.Axis(tickSize=0, labelAngle=-90, tickCount=5, title='Date')), y=alt.Y('value', title='Count'), color='variable') # Create a selection that chooses the nearest point & selects based on x-value nearest = alt.selection(type='single', nearest=True, on='mouseover', fields=['date'], empty='none') # Transparent selectors across the chart. This is what tells us # the x-value of the cursor selectors = alt.Chart(source).mark_point().encode( x='date', opacity=alt.value(0)).add_selection(nearest) # Draw points on the line, and highlight based on selection points = line.mark_point().encode( opacity=alt.condition(nearest, alt.value(1), alt.value(0))) # Draw text labels near the points, and highlight based on selection text = line.mark_text( align='left', dx=5, dy=-5).encode(text=alt.condition(nearest, 'value:Q', alt.value(' '))) # Draw a rule at the location of the selection rules = alt.Chart(source).mark_rule(color='gray').encode( x='date', ).transform_filter(nearest) # Put the five layers into a chart and bind the data layers = alt.layer(line.mark_line(), selectors, points, text, rules) return layers
def _select(self): """Create a selection that chooses the nearest point & selects based on x-value """ nearest = alt.selection(type='single', nearest=True, on='mouseover', fields=[self.target], empty='none') # Selection in a legend self.leg = alt.selection_multi(fields=['показатель'], bind='legend') # Draw a chart self.line = self.draw.encode(alt.X(self.target, type='temporal', title=' ', axis=alt.Axis(grid=self.grid, offset=10)), alt.Y('y', type=self.type_, title='количество', scale=alt.Scale(zero=False), axis=alt.Axis(grid=self.grid, offset=10)), alt.Color('показатель:N', legend=self.legend), opacity=alt.condition( self.leg, alt.value(1), alt.value(0.2))) # Transparent selectors across the chart. This is what tells us # the x-value of the cursor self.selectors = alt.Chart(self.data).mark_point().encode( alt.X(self.target, type='temporal'), opacity=alt.value(0), ).add_selection(nearest) # Draw points on the line, and highlight based on selection self.points = self.line.mark_point().encode( opacity=alt.condition(nearest, alt.value(1), alt.value(0))) # Draw text labels near the points, and highlight based on selection self.text = self.line.mark_text( align='right', dx=-5, fill='#000000', fontSize=16, clip=False).encode(text=alt.condition( nearest, 'y', alt.value(''), type=self.type_)) # Draw X value on chart self.x_text = self.line.mark_text( align="left", dx=-5, dy=15, fill='#808080', fontSize=16).encode(text=alt.condition(nearest, self.target, alt.value(''), type='temporal', format='%Y-%m-%d')) # Draw a rule at the location of the selection self.rules = alt.Chart(self.data).mark_rule(color='gray').encode( alt.X(self.target, type='temporal')).transform_filter(nearest)
def plot_interactive_lines(data, x, y, hue, alpha=0.2, point_size=15, line_size=1.5): """ Use altair to plot multiple lines with interactive selection """ highlight = alt.selection(type='single', fields=[hue], on='mouseover', nearest=True, bind='legend') selection = alt.selection_multi(fields=[hue], on='mouseover', bind='legend') base = alt.Chart(data).encode( x=x, y=y, color=hue, tooltip=[hue], ) points = base.mark_circle().encode( opacity=alt.condition(selection, alt.value(1), alt.value(alpha)), size=alt.condition(~highlight, alt.value(point_size), alt.value(point_size * 2))).add_selection(highlight) lines = base.mark_line().encode( opacity=alt.condition(selection, alt.value(1), alt.value(alpha)), size=alt.condition(~highlight, alt.value(line_size), alt.value(line_size * 2))).add_selection(selection) return lines + points
def data_make(self): click = alt.selection(type='multi', encodings=['x', 'y']) scatter1 = alt.Chart(self.cars).mark_point().encode( alt.X('Horsepower:Q', scale=alt.Scale(type='log', domain=(30, 300)), axis=alt.Axis(title='Horsepawer[MPa]')), alt.Y('Miles_per_Gallon:Q', scale=alt.Scale(domain=(0, 50))), color=alt.condition(click, 'Origin:N', alt.value('lightgray'), legend=None), tooltip=['Name:N']).properties(selection=click, title='Once a famous cars data') base = alt.Chart(self.cars).mark_point().encode( alt.X('Cylinders:N'), alt.Y('Origin:N'), color=alt.condition( click, 'Origin:N', alt.value('lightgray'), legend=None)).properties( selection=click, title='Data selector with [Click + Shift-key]') return (base | scatter1)
def add_ruler_as_selector_on_single_line_chart(chart: Any, df: pd.DataFrame, x_field: str, y_field: str) -> Any: # Create a selection that chooses the nearest point & selects based on x-value nearest = alt.selection( type="single", nearest=True, on="mouseover", fields=[typedef.Columns.DATE], empty="none", ) # Transparent selectors across the chart. This is what tells us # the x-value of the cursor selectors = (alt.Chart(df).mark_point().encode( x=x_field, opacity=alt.value(0), tooltip=alt.Tooltip(y_field), ).add_selection(nearest)) # Draw points on the line, and highlight based on selection points = chart.mark_point().encode(opacity=alt.condition( nearest, alt.value(1), alt.value(0)), ) # # Draw text labels near the points, and highlight based on selection # text = chart.mark_text(align="left", dx=5, dy=-5).encode( # text=alt.condition(nearest, y_field, alt.value(" ")) # ) # Draw a rule at the location of the selection rules = (alt.Chart(df).mark_rule(color="gray").encode( x=x_field).transform_filter(nearest)) # Put the five layers into a chart and bind the data return alt.layer(chart, selectors, points, rules)
def combined_bar_line_plot(df, y, x): brush = alt.selection(type="interval", encodings=["x"]) base = barplot(df, y, x) upper = base.encode(alt.X(x, scale=alt.Scale(domain=brush))) lower = base.mark_line().properties(height=120).add_selection(brush) combined = alt.vconcat(upper, lower) return combined
def state_google(state_only_input): to_plot = google_states[google_states.sub_region_1 == state_only_input] id_vars = ['date'] value_vars = to_plot.columns[4:] to_plot = to_plot.melt(id_vars, value_vars, var_name = 'type', value_name = 'volume') highlight = alt.selection(type='single', on='mouseover', fields=['type'], nearest=True) base = alt.Chart(to_plot).mark_line().encode( x = 'date:T', y = alt.Y('volume:Q', title = 'Relative volume'), color = alt.Color('type:N', title = "Destination type") ).properties( title = {'text': 'Traffic by Destination Type', 'subtitle': 'Source: Google mobility data'}, height = 300 ) points = base.mark_circle().encode( opacity=alt.value(0) ).add_selection( highlight ).properties( width=600 ) lines = base.mark_line().encode( size=alt.condition(~highlight, alt.value(1), alt.value(3)) ) return points + lines
def movie_embedding_norm(models): """Visualizes the norm and number of ratings of the movie embeddings. Args: model: A MFModel object. """ if not isinstance(models, list): models = [models] df = pd.DataFrame({ 'title': movies['title'], 'genre': movies['genre'], 'num_ratings': movies_ratings['rating count'], }) charts = [] brush = alt.selection_interval() for i, model in enumerate(models): norm_key = 'norm' + str(i) df[norm_key] = np.linalg.norm(model.embeddings["movie_id"], axis=1) nearest = alt.selection( type='single', encodings=['x', 'y'], on='mouseover', nearest=True, empty='none') base = alt.Chart().mark_circle().encode( x='num_ratings', y=norm_key, color=alt.condition(brush, alt.value('#4c78a8'), alt.value('lightgray')) ).properties( selection=nearest).add_selection(brush) text = alt.Chart().mark_text(align='center', dx=5, dy=-5).encode( x='num_ratings', y=norm_key, text=alt.condition(nearest, 'title', alt.value(''))) charts.append(alt.layer(base, text)) return altair_viewer.show(alt.hconcat(*charts, data=df))
def line_chart(df_melted, y_axis, title): nearest = alt.selection(type='single', nearest=True, on='mouseover', fields=['Year'], empty='none') selectors = alt.Chart(df_melted).mark_point().encode( x='Year:Q', opacity=alt.value(0), ).add_selection(nearest) line = alt.Chart(df_melted).mark_line(color=color).encode( x=alt.X('Year:Q', axis=alt.Axis(tickCount=forecast_period), sort=list(df_melted.index)), y=alt.Y(y_axis), tooltip=[alt.Tooltip(y_axis, format=',.0%')]) points = line.mark_point(color=color, size=40).encode( opacity=alt.condition(nearest, alt.value(1), alt.value(0))) chart = alt.layer(line, selectors, points).properties(title=title, width=alt.Step(60), height=400).interactive() return chart
def tv_linkedScatterPlot(data, engine, xlabel, ylabel1, ylabel2): data = data.copy() # data['year'] = data.apply(lambda x : x.name.year, axis=1) data.rename(columns={ 'plotY': xlabel, 'plotX1': ylabel1, 'plotX2': ylabel2 }, inplace=True) interval = alt.selection(type='interval', encodings=['x', 'y']) base = alt.Chart(data) base = base.mark_point() lplot = base.encode(x=ylabel1, y=alt.Y('{0}:Q'.format(xlabel), axis=alt.Axis(format='~s')), color=alt.condition(interval, 'anfreq_label', alt.value('lightgray'))) lplot = lplot.properties(selection=interval, width=260, height=300) rplot = base.encode(x=ylabel2, y=alt.Y('{0}:Q'.format(xlabel), title='', axis=alt.Axis(labels=False)), color=alt.condition(interval, 'anfreq_label', alt.value('lightgray'))) rplot = rplot.properties(selection=interval, width=260, height=300) p = alt.hconcat(lplot, rplot, spacing=0) return p
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.5), ) .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
def plot_both(county='alle_fylker', start=False, end=False, range='day'): data = fetch_data(county, start, end, range) if range == 'day': dato = 'Prøvetakingsdato:T' else: dato = 'Dato:T' cum = 'Kumulativt antall:Q' new = 'Nye tilfeller:Q' nearest = alt.selection(type='single', nearest=True, on='mouseover', fields=['Prøvetakingsdato']) base = alt.Chart(data).encode(x=dato, tooltip=[ alt.Tooltip(dato, title='dato'), alt.Tooltip(new, title='nye tilfeller'), alt.Tooltip( cum, title='kumulative tilfeller'), ]).mark_bar().encode(y=new) line = base.mark_line(color='red').encode(y=cum, tooltip=[cum]) final = alt.layer(base, line).resolve_scale(y='independent').interactive() return final
""" Interactive Chart with Cross-Highlight ====================================== This example shows an interactive chart where selections in one portion of the chart affect what is shown in other panels. Click on the bar chart to see a detail of the distribution in the upper panel. """ # category: interactive charts import altair as alt from vega_datasets import data source = data.movies.url pts = alt.selection(type="single", encodings=['x']) rect = alt.Chart(data.movies.url).mark_rect().encode( alt.X('IMDB_Rating:Q', bin=True), alt.Y('Rotten_Tomatoes_Rating:Q', bin=True), alt.Color('count()', scale=alt.Scale(scheme='greenblue'), legend=alt.Legend(title='Total Records') ) ) circ = rect.mark_point().encode( alt.ColorValue('grey'), alt.Size('count()', legend=alt.Legend(title='Records in Selection') ) ).transform_filter( pts
""" Selection Histogram =================== This chart shows an example of using an interval selection to filter the contents of an attached histogram, allowing the user to see the proportion of items in each category within the selection. """ # category: interactive charts import altair as alt from vega_datasets import data source = data.cars() brush = alt.selection(type='interval') points = alt.Chart().mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', color=alt.condition(brush, 'Origin:N', alt.value('lightgray')) ).add_selection( brush ) bars = alt.Chart().mark_bar().encode( y='Origin:N', color='Origin:N', x='count(Origin):Q' ).transform_filter( brush )
""" Multi-panel Scatter Plot with Linked Brushing --------------------------------------------- This is an example of using an interval selection to control the color of points across multiple panels. """ # category: interactive charts import altair as alt from vega_datasets import data source = data.cars() brush = alt.selection(type='interval', resolve='global') base = alt.Chart(source).mark_point().encode( y='Miles_per_Gallon', color=alt.condition(brush, 'Origin', alt.ColorValue('gray')) ).add_selection( brush ).properties( width=250, height=250 ) base.encode(x='Horsepower') | base.encode(x='Acceleration')
""" Multi-Line Highlight ==================== This multi-line chart uses an invisible Voronoi tessellation to handle mouseover to identify the nearest point and then highlight the line on which the point falls. It is adapted from the Vega-Lite example found at https://bl.ocks.org/amitkaps/fe4238e716db53930b2f1a70d3401701 """ # category: interactive charts import altair as alt from vega_datasets import data source = data.stocks() highlight = alt.selection(type='single', on='mouseover', fields=['symbol'], nearest=True) base = alt.Chart(source).encode( x='date:T', y='price:Q', color='symbol:N' ) points = base.mark_circle().encode( opacity=alt.value(0) ).add_selection( highlight ).properties( width=600 )
Interactive Crossfilter ======================= This example shows a multi-panel view of the same data, where you can interactively select a portion of the data in any of the panels to highlight that portion in any of the other panels. """ # category: interactive charts import altair as alt from vega_datasets import data source = alt.UrlData( data.flights_2k.url, format={'parse': {'date': 'date'}} ) brush = alt.selection(type='interval', encodings=['x']) # Define the base chart, with the common parts of the # background and highlights base = alt.Chart().mark_bar().encode( x=alt.X(alt.repeat('column'), type='quantitative', bin=alt.Bin(maxbins=20)), y='count()' ).properties( width=180, height=130 ) # blue background with selection background = base.properties(selection=brush) # yellow highlights on the transformed data
states = alt.topo_feature(data.us_10m.url, 'states') capitals = data.us_state_capitals.url # US states background background = alt.Chart(states).mark_geoshape( fill='lightgray', stroke='white' ).properties( title='US State Capitols', width=700, height=400 ).project('albersUsa') # Points and text hover = alt.selection(type='single', on='mouseover', nearest=True, fields=['lat', 'lon']) base = alt.Chart(capitals).encode( longitude='lon:Q', latitude='lat:Q' ) text = base.mark_text(dy=-5, align='right').encode( alt.Text('city', type='nominal'), opacity=alt.condition(~hover, alt.value(0), alt.value(1)) ) points = base.mark_point().encode( color=alt.value('black'), size=alt.condition(~hover, alt.value(30), alt.value(100)) ).add_selection(hover)
The following example employs a little trick to isolate the x-position of the cursor: we add some transparent points with only an x encoding (no y encoding) and tie a *nearest* selection to these, tied to the "x" field. """ # category: interactive charts import altair as alt import pandas as pd import numpy as np np.random.seed(42) source = pd.DataFrame(np.cumsum(np.random.randn(100, 3), 0).round(2), columns=['A', 'B', 'C'], index=pd.RangeIndex(100, name='x')) source = source.reset_index().melt('x', var_name='category', value_name='y') # Create a selection that chooses the nearest point & selects based on x-value nearest = alt.selection(type='single', nearest=True, on='mouseover', fields=['x'], empty='none') # The basic line line = alt.Chart().mark_line(interpolate='basis').encode( x='x:Q', y='y:Q', color='category:N' ) # Transparent selectors across the chart. This is what tells us # the x-value of the cursor selectors = alt.Chart().mark_point().encode( x='x:Q', opacity=alt.value(0), ).add_selection( nearest
""" # category: interactive charts import altair as alt import pandas as pd import numpy as np x = np.random.normal(size=100) y = np.random.normal(size=100) m = np.random.normal(15, 1, size=100) source = pd.DataFrame({"x": x, "y":y, "m":m}) # interval selection in the scatter plot pts = alt.selection(type="interval", encodings=["x"]) # left panel: scatter plot points = alt.Chart().mark_point(filled=True, color="black").encode( x='x', y='y' ).transform_filter( pts.ref() ).properties( width=300, height=300 ) # right panel: histogram mag = alt.Chart().mark_bar().encode( x='mbin:N',