def data_waterfall(): chart = Chart(sample_data.df_water).mark_bar(color='gray').encode( X('Name', axis=Axis(title='Sample')), Y('Value', axis=Axis(title='Value'))).interactive() return chart.to_json()
def data_line(): chart = Chart(data=sample_data.df_list, height=HEIGHT, width=WIDTH).mark_line(color='green').encode( X('name', axis=Axis(title='Sample')), Y('data', axis=Axis(title='Value'))).interactive() return chart.to_json()
def hc_grade(): session_id = os.environ.get("SESSION_ID") selected_course = session.get('selected_course', None) # show all course grades if haven't selected course from dropdown if selected_course == None: HcData = pd.read_sql(db.session.query(Hc).filter_by(user_id=session_id).statement, db.session.bind) final = Chart( data=HcData, height=1000, width=380).mark_bar().encode( X('mean:Q', axis=alt.Axis(title='HC Forum Score'), scale=Scale(domain=(0, 5)) ), alt.Y('name:N', sort=alt.EncodingSortField(field= "mean", op="sum", order = "descending") ,axis=alt.Axis(title=None) ), color='course:N')#.interactive() else: # query data df = grade_calculations.hc_grade_over_time(session_id, selected_course) longdata = df.melt('Date', var_name='course', value_name='grade') data = longdata[longdata['grade'].notnull()] def getBaseChart(): """ Creates a chart by encoding the Data along the X positional axis and rolling mean along the Y positional axis """ base = ( alt.Chart(data) .encode( x=alt.X( "Date:T", axis=alt.Axis(title=None, format=("%b %Y"), labelAngle=0), ), y=alt.Y( "grade:Q", axis=alt.Axis(title=None), scale=Scale(domain=(0, 5)) ), color=alt.Color('course:N', legend=None) ).properties(width=400, height=336) ) return base def getSelection(): """ This function creates a selection element and uses it to conditionally set a color for a categorical variable (course). It return both the single selection as well as the Category for Color choice set based on selection. """ radio_select = alt.selection_multi( fields=["course"], name="Course", ) course_color_condition = alt.condition( radio_select, alt.Color("course:N", legend=None), alt.value("lightgrey") ) return radio_select, course_color_condition def createChart(): """ This function uses the "base" encoding chart to create a line chart. The highlight_course variable uses the mark_line function to create a line chart out of the encoding. The color of the line is set using the conditional color set for the categorical variable using the selection. The chart is bound to the selection using add_selection. It also creates a selector element of a vertical array of circles so that the user can select between courses. """ radio_select, course_color_condition = getSelection() make_selector = ( alt.Chart(data) .mark_circle(size=220) .encode( y=alt.Y("course:N", title="Click on circle"), color=course_color_condition ).add_selection(radio_select) ) base = getBaseChart() highlight_course = ( base.mark_line(strokeWidth=2) .add_selection(radio_select) .encode(color=course_color_condition, opacity=alt.condition(radio_select, alt.value(1.0), alt.value(0.2))) ).properties(title="Rolling Weighted Average of Cornerstone Courses") return base, make_selector, highlight_course, radio_select def createTooltip(base, radio_select): """ This function uses the "base" encoding chart and the selection captured. Four elements related to selection are created here """ # 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(data) .mark_point() .encode( x="Date:T", opacity=alt.value(0), ).add_selection(nearest) ) # Draw points on the line, and highlight based on selection points = base.mark_point().encode( color=alt.Color("course:N", legend=None), opacity=alt.condition(nearest, alt.value(1), alt.value(0)) ).transform_filter(radio_select) # Draw text labels near the points, and highlight based on selection tooltip_text = base.mark_text( align="left", dx=5, dy=-5, fontSize=12 # fontWeight="bold" ).encode( text=alt.condition( nearest, alt.Text("grade:Q", format=".2f"), alt.value(" "), ), ).transform_filter(radio_select) # Draw a rule at the location of the selection rules = ( alt.Chart(data) .mark_rule(color="black", strokeWidth=1) .encode( x="Date:T", ).transform_filter(nearest) ) return selectors, rules, points, tooltip_text base, make_selector, highlight_course, radio_select = createChart() selectors, rules, points, tooltip_text = createTooltip(base, radio_select) # Bring all the layers together with layering and concatenation final = (make_selector | alt.layer(highlight_course, selectors, points, rules, tooltip_text)) return final.to_json()
def county_scatter(): state_name = session.get('current_state') county_name = session.get('current_county') # Connect to the database conn = sqlite3.connect('./db/incarceration.db') # Determine whether 2015 or 2016 has more data year_2016_nulls = test_nulls_for_year(2016, state_name, conn) year_2015_nulls = test_nulls_for_year(2015, state_name, conn) year = 2016 # default year # Test to see if 2015 has more non-null values if year_2016_nulls.iloc[0]['PercentNotNull'] < year_2015_nulls.iloc[0][ 'PercentNotNull']: year = 2015 # Select prison population data for the entire state for the selected year all_counties_prison_pop = pd.read_sql_query( f"""SELECT county_name, total_pop, total_prison_pop, urbanicity FROM incarceration WHERE state = '{state_name}' AND year = {year}; """, conn) # Select prison population data for the specific county for the selected year county_prison_pop = pd.read_sql_query( f"""SELECT county_name, total_pop, total_prison_pop, urbanicity FROM incarceration WHERE state = '{state_name}' AND county_name = '{county_name}' AND year = {year}; """, conn) # Close connection conn.close() state_chart = Chart( data=all_counties_prison_pop, height=HEIGHT, width=WIDTH).mark_circle(size=70).encode( X('total_pop', axis=Axis(title='County population')), Y('total_prison_pop', axis=Axis(title='Total prison population')), color=alt.Color('urbanicity', legend=alt.Legend(title='Urbanicity')), size=alt.Color('total_pop', legend=alt.Legend(title='Total population')), tooltip=[ alt.Tooltip('county_name', title='County'), alt.Tooltip('total_pop', title='Total county population'), alt.Tooltip('total_prison_pop', title='Total prison population') ], ).properties(title='Statewide prison population {}, {}'.format( year, state_name)).interactive() county_chart = Chart( data=county_prison_pop, height=HEIGHT, width=WIDTH).mark_square( size=250, fillOpacity=0.5, stroke='black', color='black').encode( X('total_pop', axis=Axis(title='County population')), Y('total_prison_pop', axis=Axis(title='Total prison population')), tooltip=['county_name', 'total_pop', 'total_prison_pop']).interactive() chart = alt.layer(county_chart, state_chart) return chart.to_json()
result['Time'] = result.apply(lambda row: news(row) , axis=1) df_dados = result.loc[:][['Rodada','Temporada','Time','Resultado']].copy() df_dados.sort_values(by=['Rodada'] ,ascending=True , inplace=True) df_dados['Acumulado'] = df_dados.groupby(['Temporada','Time'])[['Time','Resultado']].cumsum() x = st.slider('Selecione o ano',2012, 2019, (2012)) df_dados = df_dados[df_dados['Temporada'] == x].reset_index(drop=True) st.dataframe(df_dados) bars = alt.Chart(df_dados).mark_bar().encode( x=X('2:Q',axis=Axis(title='Brasileirao')), y=Y('0:Q',axis=Axis(title='Times')) ).properties( width=650, height=400 ) bar_plot = st.altair_chart(bars) def plot_bar_animated_altair(df,week): bars = alt.Chart(df, title="Ranking por Rodada :"+week) for week in range(1,39): teste = str(week) bars = plot_bar_animated_altair(df_dados[df_dados['Rodada']== teste],teste) time.sleep(0.01)
def data_line(): chart = Chart(data=data.df_list, height=HEIGHT, width=WIDTH).mark_line().encode( X('name', axis=Axis(title='Sample')), Y('data', axis=Axis(title='Value'))) return chart.to_json()
def data_waterfall(): chart = Chart(data.df_water).mark_bar(color='lightgreen').encode( X('Name', axis=Axis(title='Sample')), Y('Value', axis=Axis(title='Value'))) return chart.to_json()
import pandas as pd import numpy as np from altair import Chart, X, Y, SortField, Detail, Axis csv_path = "../data/dropped-frames.csv" df = pd.read_csv(csv_path, parse_dates=["Dropped Frame Start", "Dropped Frame End"], low_memory=False) data = df[['Officer ID', 'Dropped Frame Start', 'Duration', 'FPS', 'Dropped Frames', 'Resolution', 'File Size', 'File Name', 'Frame Range', 'Player Time Range']] data = data.rename(columns={'Dropped Frame Start': 'Timestamp'}) ## Overview Chart(data.sample(100)).configure_axis(gridColor='#ccc').mark_line(interpolate='linear').encode( X(field='Timestamp', type='temporal', timeUnit='yearmonth', axis=Axis(title=' ', ticks=6, labelAngle=0, tickSizeEnd=0, tickSize=0, tickPadding=10)), Y('sum(Duration)', axis=Axis(title='Seconds lost')) ).savechart('test.svg')
def chartLog(): "Display chart for selected log" db_folder = app.config['UPLOAD_FOLDER'] logFiles = glob.glob('%s/*.db' % db_folder) form = ChartLog() form.logFile.choices = [(f, f) for f in logFiles] form.chartId.choices = [(q['id'], q['id']) for q in queries.graphs] try: dbname = app.dbname if os.path.exists(dbname): form.logFile.data = dbname except: pass if not form.validate_on_submit(): return render_template('chartLog.html', chart={}, dbName=None, form=form) dbname = os.path.join(form.logFile.data) if not os.path.exists(dbname): flash('Database does not exist', 'error') return render_template('error.html', title='Database error') try: conn = sqlite3.connect(dbname) except Exception as e: app.logger.error(traceback.format_exc()) flash('Error: %s' % (str(e)), 'error') return render_template('error.html', title='Error in database reporting') chartId = form.chartId.data charts = [q for q in queries.graphs if q['id'] == chartId] if not charts: flash("Error: logic error couldn't find chartId", 'error') return render_template( 'error.html', title='Error in in configuration of chart reports') q = charts[0] app.logger.debug("running chart query: %s - %s" % (q['title'], q['sql'])) start = datetime.now() try: df = pd.read_sql_query(q['sql'], conn) except Exception as e: flash('Error: %s' % (str(e)), 'error') return render_template('error.html', title='Error in database reporting') end = datetime.now() delta = end - start if q['graph_type'] == 'line': chart = Chart(data=df, height=HEIGHT, width=WIDTH).mark_line().encode( X(q['x']['field'], axis=Axis(title=q['x']['title'], labelOverlap='greedy')), Y(q['y']['field'], axis=Axis(title=q['y']['title']))) else: chart = Chart(data=df, height=HEIGHT, width=WIDTH).mark_bar().encode( X(q['x']['field'], axis=Axis(title=q['x']['title'], labelOverlap='greedy')), Y(q['y']['field'], axis=Axis(title=q['y']['title']))) data = { 'id': "chart", 'data': chart.to_json(), 'title': q['title'], 'explanation': q['explanation'], 'sql': q['sql'], 'time_taken': str(delta) } return render_template('chartLog.html', chart=data, dbName=dbname, form=form)