def build_graph(graph_type, x_axis, y_axis, color): dff = df if graph_type == 'LINE': fig = px.line(dff, x=x_axis, y=y_axis, color=color, height=600) fig.update_layout(yaxis={'title': y_axis}, title={ 'text': x_axis + ' vs ' + y_axis, 'font': { 'size': 28 }, 'x': 0.5, 'xanchor': 'center' }) elif graph_type == 'SCATTER': fig = px.scatter(dff, x=x_axis, y=y_axis, color=color, height=600) fig.update_layout(yaxis={'title': y_axis}, title={ 'text': x_axis + ' vs ' + y_axis, 'font': { 'size': 28 }, 'x': 0.5, 'xanchor': 'center' }) elif graph_type == 'BAR': fig = px.bar(dff, x=x_axis, y=y_axis, color=color, height=600) fig.update_xaxes(type='category') fig.update_layout(yaxis={'title': y_axis}, title={ 'text': x_axis + ' vs ' + y_axis, 'font': { 'size': 28 }, 'x': 0.5, 'xanchor': 'center' }) elif graph_type == 'AREA': fig = px.area(dff, x=x_axis, y=y_axis, color=color, height=600) fig.update_layout(yaxis={'title': y_axis}, title={ 'text': x_axis + ' vs ' + y_axis, 'font': { 'size': 28 }, 'x': 0.5, 'xanchor': 'center' }) elif graph_type == 'HEET': fig = px.density_heatmap(dff, x=x_axis, y=y_axis, nbinsx=20, nbinsy=20, marginal_x="histogram", marginal="histogram") elif graph_type == 'BOX': fig = px.box(dff, x=x_axis, y=y_axis, color=color, height=600) fig.update_layout(yaxis={'title': y_axis}, title={ 'text': x_axis + ' vs ' + y_axis, 'font': { 'size': 28 }, 'x': 0.5, 'xanchor': 'center' }) elif graph_type == 'PIE': fig = px.pie(dff, values=x_axis, names=y_axis, height=600) fig.update_layout(yaxis={'title': y_axis}, title={ 'text': x_axis + ' vs ' + y_axis, 'font': { 'size': 28 }, 'x': 0.5, 'xanchor': 'center' }) elif graph_type == 'HIST': fig = px.histogram(dff, x=x_axis, y=y_axis, marginal="box", color=color, height=600) # can be box or violin fig.update_layout(yaxis={'title': y_axis}, title={ 'text': x_axis + ' vs ' + y_axis, 'font': { 'size': 28 }, 'x': 0.5, 'xanchor': 'center' }) elif graph_type == 'SMX': fig = px.scatter_matrix(dff, color=color) fig.update_layout(yaxis={'title': y_axis}, title={ 'text': x_axis + ' vs ' + y_axis, 'font': { 'size': 28 }, 'x': 0.5, 'xanchor': 'center' }) elif graph_type == 'VIOLIN': fig = px.violin(dff, x=x_axis, y=y_axis, box=True, color=color, height=600) # can be box or violin fig.update_layout(yaxis={'title': y_axis}, title={ 'text': x_axis + ' vs ' + y_axis, 'font': { 'size': 28 }, 'x': 0.5, 'xanchor': 'center' }) return fig
html.P(id='metadata-periods-docs', style={'text-align': 'center'}), dbc.InputGroup([ dbc.InputGroupAddon('Select value to show: ', addon_type='prepend'), dbc.Select(options=[{ 'label': 'Journal', 'value': 'journal_id' }, { 'label': 'Language', 'value': 'lang' }], id='metadata-pie-values-select', value='journal_id'), ], style={'max-width': '60%'}), dcc.Graph(id='metadata-periods-pie', figure=px.pie()) ]) ]) # tab container, which is imported by tabindex # divided in rows with dbc.Row() and then cols with dbc.Col() # each col typically holds one card metadata_tab_layout = dbc.Container( [ dbc.Row([ dbc.Col([meta_card_bar], width=12), #dbc.Col([ #meta_card_pie #], width=4), ]), ],
def create_app_ui(): global df global df_etsy df_etsy = pd.read_csv('etsy_product_review.csv') df = df.dropna() df = df[df['overall'] != 3] df['Positivity'] = np.where(df['overall'] > 3, 'Positive', 'Negative') labels = ['Positive Reviews', 'Negative Reviews'] values = [len(df[df.Positivity == 1]), len(df[df.Positivity == 0])] main_layout = html.Div( style={'backgroundColor': colors['background']}, children=[ html.H1(children='SENTIMENT ANALYSIS WITH INSIGHTS', id='Main_title', style={ 'textAlign': 'center', 'color': '#0A0865' }), #piechart html.H1([ html.P(children="Balanced Reviews Pie Chart", id="heading1", style={ 'textAlign': 'center', 'font-size': '20px', 'color': 'white', 'background-color': '#0A0865' }), dcc.Graph( figure=px.pie(data_frame=df, names='Positivity', color_discrete_sequence=["red", "green"], template='plotly_dark').update_layout( { 'plot_bgcolor': 'rgba(0, 0, 0, 0)', 'paper_bgcolor': 'rgba(0, 0, 0, 0)' }, )) ]), html.H1(children='Check Review Sentiment', id='title2', style={ 'textAlign': 'center', 'font-size': '20px', 'color': 'white', 'background-color': '#0A0865' }), dcc.Textarea( id='textarea_review', placeholder='Enter the review here...', #value='My daughter loves these shoes', style={ 'width': '100%', 'height': 50 }), html.Br(), html.Button(id='button_click', children='Find review sentiment', n_clicks=0, style={ 'text-align': 'center', 'color': 'Blue' }), html.H1(id='result', children=None, style={ 'text-align': 'center', 'color': 'White', 'backgroundColor': '#0A0865', 'fontSize': 30 }), html.Br(), dcc.Dropdown( id='review_dropdown', options=[{ 'label': i, 'value': i } for i in df_etsy['review'].sample(10)], placeholder='Select a review for Etsys Star Hoop Earrings', style={ 'width': '100%', 'height': 20, 'margin-bottom': '30px' }), html.Button(id='button_click1', children='Find review sentiment', n_clicks=0, style={ 'text-align': 'center', 'color': 'Blue' }), html.H1(id='result1', children=None, style={ 'text-align': 'center', 'color': 'White', 'backgroundColor': '#0A0865', 'fontSize': 30 }) ]) return main_layout
fig1 = px.line(a.cumsum(), y=a.columns[0], labels={'fecha reporte web': 'Fecha de reporte'}, title="Histórico de casos reportados en " + report_name) st.plotly_chart(fig1) # Graph of diagnostic cases per day fig2 = px.line(a, y=a.columns[0], labels={'fecha reporte web': 'Fecha de reporte'}, title="Histórico de casos diarios reportados en " + report_name) st.plotly_chart(fig2) # Pie diagram according to the location of the patient's case fig_A = px.pie(e.reset_index(), values='Número de pacientes', names='Recuperado', title='Distribución por atención de casos reportados') st.plotly_chart(fig_A) # Pie diagram according to the status of the patients fig_B = px.pie(b.reset_index(), values='Número de pacientes', names='Estado', title='Distribución por estado de casos reportados') st.plotly_chart(fig_B) # Summary report is shown just if record type selected is either nacional or departmental if tipo_reporte != 'Municipal': st.header("Resumen " + tipo_reporte.lower()) fig_C = px.bar(c, x=c.columns[0],
def employeeOverview(**props): flask_app = props["app"] # type: Flask dash_app = props["dash_app"] # type: Dash def calculate_critical_employees( username, password, database, url ): data = load_odoo_data( username, password, database, url, flask_app ) critical_employees = None non_critical_employees = None number_of_employees = data.shape[0] if number_of_employees > 0 : critical_employees = 0 for index, row in data.iterrows(): if row['x_employee_work_criticality'] is True: critical_employees += 1 non_critical_employees = number_of_employees - critical_employees return { 'critical_employees' : critical_employees, 'non_critical_employees': non_critical_employees, 'employees': number_of_employees if number_of_employees > 0 else None } username = None password = None database = None url = None with flask_app.app_context(): username = flask_app.config["ODOO_USERNAME"] password = flask_app.config["ODOO_PASSWORD"] database = flask_app.config["ODOO_DATABASE"] url = flask_app.config["ODOO_URL"] data_dict = calculate_critical_employees( username, password, database, url ) pieChart = px.pie( { "Name Of Section": ["Critical Employees", "Non Critical Employees"], "Number of Employees": [ data_dict.get("critical_employees"), data_dict.get("non_critical_employees") ] }, names="Name Of Section", values="Number of Employees" ) @dash_app.callback( [ Output( component_id = "employee-overview-number-of-employees", component_property="children" ), Output( component_id= "employee-overview-number-of-critical-employees", component_property="children" ), Output( component_id= "employee-overview-pie-chart", component_property="figure" ) ], [ Input( component_id='interval-component', component_property='n_intervals' ) ] ) def calculate_changes(n): data_dict = calculate_critical_employees( username, password, database, url ) pieChart = px.pie( { "Name Of Section": ["Critical Employees", "Non Critical Employees"], "Number of Employees": [ data_dict.get("critical_employees"), data_dict.get("non_critical_employees") ] }, names="Name Of Section", values="Number of Employees" ) num_employees = str(data_dict.get("employees")) critical_employees = str(data_dict.get("critical_employees")) return num_employees, critical_employees, pieChart return html.Div( className="elementContainer", children = [ html.Div( className="numberOfEmployeesContainer", children = [ html.H2("Number of Employees"), html.P( id="employee-overview-number-of-employees", children = str(data_dict.get("employees")) ) ] ), html.Div( className="numberOfCriticalEmployeesContainer", children = [ html.H3("Number of Critical Employees"), html.P( id="employee-overview-number-of-critical-employees", children = str(data_dict.get('critical_employees')) ) ] ), html.Div( className="employeesPieChartContainer", children = [ html.H3("Employees Criticality Pie Chart"), dcc.Graph( id="employee-overview-pie-chart", responsive=True, figure = pieChart, style = { "width": "100%", "height": "300px" } ) ] ) ] )
app = dash.Dash(__name__, external_stylesheets=external_stylesheets) colors = {'background': '#e2e2e2', 'text': 'blue'} fig2 = px.bar(df, x="Survived", y=df.Fare.astype('int64'), color="Sex", barmode="group") fig2.update_layout(plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], font_color=colors['text']) fig3 = px.pie(df, values='Fare', names='Survived', title='Total Fare based on Survived') pass_sum1 = df.groupby(['Pclass']).Survived.sum() fig4 = px.bar(pass_sum1, barmode='group', title='Survived Passengers Count based on Pclass') fig4.update_layout(plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], font_color=colors['text']) app.layout = html.Div([ html.H1(children='Titanic Dash', style={ 'textAlign': 'center',
'%s, %1.1f%%' % (l, (float(s) / total) * 100) for l, s in zip(labels, sizes) ], prop={'size': 11}, bbox_to_anchor=(0.0, 1), bbox_transform=fig1.transFigure) plt.title('Thị phần 6 nhóm sản phẩm Level 2', fontsize=14, fontweight='bold') plt.show() # $$\textbf{Nhận xét:}$$ # Có vẻ như các cách xây dựng Đồ thị miếng ở trên, ở khía cạnh nào đó, chưa rõ ràng về mặt trực quan, chúng ta hãy thử Câu lệnh dưới đây để xây dựng dạng Đồ thị miếng rõ ràng về trực quan # In[28]: fig = px.pie(record_level22, values='Số_lượng_tuyệt_đối', names=record_level22.index, title='Thị phần 6 nhóm sản phẩm Level 2') fig.show() # ### Level 3 # In[29]: record_level32 = record_level3.set_index(['Nhóm_hàng_level_3']) labels3 = record_level32['Số_lượng_tuyệt_đối'].index fig1, ax1 = plt.subplots(figsize=(6, 10)) #fig1, ax1 = plt.subplots() ax1.pie(record_level32['Số_lượng_tuyệt_đối'], labels=labels3, autopct='%1.1f%%', shadow=True,
"2019-06-01", "2019-07-01", "2019-08-01", "2019-09-01", "2019-10-01", "2019-11-01", "2019-12-01", ]) # show range selector annual_shutdowns.update_yaxes(fixedrange=False) ## Graph 2 # define second plot and aesthetics downtime_country = px.pie( df, values="duration", names="country ", title="Proportional Duration (of Total Global Downtime) by Country", ) downtime_country.update_traces(textposition='inside', textfont_size=14, textinfo="label+percent") ## Graph 3 # sum instances of social media outtages FB_count = df['Facebook_affected'].sum() TW_count = df['Twitter_affected'].sum() WA_count = df['WhatsApp_affected'].sum() TG_count = df['Telegram_affected'].sum() # create new dataframe data = [('Facebook', FB_count), ('Twitter', TW_count), ('WhatsApp', WA_count),
airline_data = pd.read_csv( 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/airline_data.csv', encoding="ISO-8859-1", dtype={ 'Div1Airport': str, 'Div1TailNum': str, 'Div2Airport': str, 'Div2TailNum': str }) # Randomly sample 500 datapoints data = airline_data.sample( n=500, random_state=42) # random seed=42, same seed=same sample # Pie chart creation fig = px.pie(data, values='Flights', names='DistanceGroup', title='Distance group propotion by flights') # Create the dash application app = dash.Dash(__name__) # Get the layout of the application # Create an outer division using html.Div and add title to the dashboard using html.H1 component # Add description about the graph using HTML P (paragraph) component # Finally, add graph component app.layout = html.Div(children=[ html.H1('Airline Dashboard', style={ 'textAlign': 'center', 'color': '#503D36', 'font-size': 40
def visualize_data(transactions: pd.DataFrame, year=2019): verify_data(transactions) transactions["expense"] = abs(transactions["Debit"]) selected_year = transactions[transactions["year"] == year].copy() balance = selected_year.groupby(["month"]).sum().reset_index() balance["balance"] = balance["Credit"] + balance["Debit"] balance["color"] = np.where(balance["balance"] < 0, "Negative", "Positive") balance["savings"] = balance["balance"].cumsum() grouped_week = (selected_year[selected_year["type"] == "grocery"].groupby( ["week"]).sum().reset_index()) fig = px.pie( selected_year, values="expense", names="type", title=f"Ratio of expenses by type in year {year}", hole=0.3, ) fig.show() fig = px.sunburst( selected_year, values="expense", path=["type", "entity"], title=f"Ratio of expenses by type and entity in year {year}", ) fig.update_traces(textinfo="label+percent entry") fig.show() fig = px.bar( balance, x="month", y="balance", color="color", barmode="stack", labels={ "color": "Balance", "balance": "Balance [EUR]", "month": "Month" }, title=f"Monthly balance in year {year}", height=400, ) fig.show() fig = px.bar( balance, x="month", y="Debit", labels={ "Debit": "Total expenses [EUR]", "month": "Month" }, title=f"Total Expenses by month in year {year}", barmode="group", height=400, ) fig.show() grouped_month_type = selected_year.groupby(["month", "type"]).sum().reset_index() fig = px.bar( grouped_month_type, x="month", y="Debit", color="type", barmode="group", labels={ "type": "Transaction type", "month": "Month", "Debit": "Expenses [EUR]", }, title=f"Total Expenses by month and type in year {year}", height=400, ) fig.show() fig = px.bar( grouped_week, x="week", y="Debit", labels={ "Debit": "Debit [EUR]", "week": "Week" }, color_discrete_sequence=["orange"], title=f"Grocery expenses by calendar week for year {year}", ) fig.show() fig = px.area( balance, x="month", y="savings", labels={ "savings": "Savings [EUR]", "month": "Month" }, color_discrete_sequence=["green"], title=f"Savings trend for year {year}", ) fig.show()
app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # Use a csv dataset from a repository in your GitHub account. Use the Raw URL to expose the data to the Python dataframe df = pd.read_csv( 'https://raw.githubusercontent.com/gonnabathula/data/master/df.csv') df2 = df df2 = df2.sort_values(by=['rating'], ascending=False) df2 = df2.head(10) df3 = df2.sort_values(by=['calories'], ascending=False) df3 = df3.head(10) df4 = df2.sort_values(by=['protein'], ascending=False) df4 = df4.head(10) fig = px.pie(df4.head(10), values='protein', names='name', title='High protein content and rating', hover_data=['rating'], labels={'rating': 'rating'}) def generate_table(dataframe, max_rows=10): return html.Table([ html.Thead(html.Tr([html.Th(col) for col in dataframe.columns])), html.Tbody([ html.Tr( [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(min(len(dataframe), max_rows)) ]) ])
def update_Pie_plot(dropdown_Pie_plot): figure = px.pie(df, values = dropdown_Pie_plot, names='Claim Type' ) return figure
) ],style = { 'paddingBottom' : '40px', } ), html.Div([ html.P('Mean Pie Chart') ], style = { 'paddingBottom' : '40px', 'text-align' : 'center' }), dcc.Graph( id = 'Pie Plot Graph', figure = px.pie(df, values = 'Claim Amount', names='Claim Type' ) ) ] ) ], style = { 'fontFamily' : 'system-ui' }, content_style = { 'fontFamily' : 'Arial', 'borderBottom' : '1px solid #000000', 'borderLeft' : '1px solid #000000', 'borderRight' : '1px solid #000000', 'padding' : '30px' }
def update_pies(species): url = ("https://data.cityofnewyork.us/resource/nwxe-4ae8.json?" +\ "$select=boroname,steward,health,count(tree_id)" +\ "&$where=spc_common='" + species +\ "'&$group=boroname,steward,health").replace(' ', '%20') nyc_df = pd.read_json(url) nyc_df = nyc_df.dropna() nyc_df['health'] = pd.Categorical(nyc_df.health, categories = hlth, ordered = True) nyc_df=nyc_df.sort_values(by='health') nyc_df['boroname'] = pd.Categorical(nyc_df.boroname, categories = boro, ordered = True) nyc_df=nyc_df.sort_values(by='boroname') fig1 = px.pie( nyc_df, values = 'count_tree_id', names = 'health', title = 'Health breakdown of %i %s trees in NYC' % (nyc_df['count_tree_id'].sum(),species), color = 'health', color_discrete_map = color_dict ) fig1.update(layout=dict(title=dict(x=0.5))) fig2 = make_subplots( rows = 1, cols = boros, subplot_titles = pie_titles, specs=[[{'type':'domain'}] * boros] ) for i in range(0,boros): boro_df = nyc_df[nyc_df['boroname']==boro[i]]#.groupby('health').agg({'count_tree_id' : 'sum'}).reset_index() colors = np.array(['']*len(boro_df['health']), dtype = object) for j in np.unique(boro_df['health']): colors[np.where(boro_df['health']==j)] = color_dict[str(j)] fig2.add_trace( go.Pie( values = boro_df['count_tree_id'], labels = boro_df['health'], marker_colors = colors, title = { 'text' : '%i Trees' % (boro_df['count_tree_id'].sum()), 'position' : 'bottom center' }, scalegroup ='one' ), row=1, col=i+1 ) fig3 = px.bar( nyc_df, x="steward", y="count_tree_id", color="health", facet_col="boroname", color_discrete_map = color_dict ) fig3.update_layout( barmode = 'relative', barnorm = 'percent', xaxis={'categoryorder': 'array', 'categoryarray': stew} ) return fig1, fig2, fig3
# Using external stylesheet for htlp formating. external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # Generating Data as required by the two questions: # Question 1: soql_url_1 = ('https://data.cityofnewyork.us/resource/nwxe-4ae8.json?' +\ '$select=health,count(tree_id)' +\ '&$group=health').replace(' ', '%20') soql_trees_1 = pd.read_json(soql_url_1) soql_trees_1.dropna(inplace=True) soql_trees_1.columns = ["Health","Count"] fig_1 = px.pie(soql_trees_1, values='Count', names='Health') # Question 2: soql_url_2 = ('https://data.cityofnewyork.us/resource/nwxe-4ae8.json?' +\ '$select=steward,health,count(tree_id)' +\ '&$group=steward,health').replace(' ', '%20') soql_trees_2 = pd.read_json(soql_url_2) soql_trees_2.dropna(inplace=True) soql_trees_2.columns = ["Stewards","Health","Count"] fig_2 = px.bar( data_frame=soql_trees_2, x="Stewards", y="Count",
fig_count.update_layout(template="plotly_dark", font_family="Arial", margin=dict(l=20, r=20, t=20, b=20)) st.plotly_chart(fig_count, use_container_width=True) #Summary plot for counts - END #Gender information-START st.subheader("It it a girl? A boy? It's a mystery! 😵") st.markdown('Did you know, it is not easy to identify the gender of kitten. ' 'We sometimes have to wait for the vet visit to get an idea') fig_gender = px.pie(original_data, # values='GENDER', names='GENDER', # x='USUAL SPOT', # y='Count', # title='Gender Distribution', # color='GENDER', # barmode='stack' # width= 400, # height= 300, ) st.plotly_chart(fig_gender, use_container_width=True) #Gender information-END #Show TNR related data on map and hexagon layer-START st.subheader("TNR Status") st.markdown('TNR stands for: Trap Neutered Release. Use the dropdown to see the list') tnr_status = st.selectbox('', ['TNR Done', 'TNR Pending', 'Unknown'])
import pandas as pd import plotly.express as px excel_book_1_relative_path = 'Purchases - Home B.xlsx' excel_book_prices = 'PriceBook.xlsx' df_prices = pd.read_excel(excel_book_prices) df_home_1 = pd.read_excel(excel_book_1_relative_path) #print(df_prices, df_home_1) df_total = df_home_1.merge(df_prices, on='ID') df_total['Total Price'] = df_total['PURCHASED AMOUNT'] * df_total['Price'] #print(df_total) fig = px.pie(df_total[['MATERIAL', 'Total Price']], values='Total Price', names='MATERIAL') fig.show()
def visualisationAge(request): # allUsersBD = UserData.objects.values('bdate') # print(allUsersBD) allUsersAge = [] allUsersAgeFiltered = [] allUsersAgeFilteredSorted = [] for i in UserData.objects.all(): if i.bdate: j = i.bdate if calculate_age(j) != None: age = calculate_age(j) allUsersAge.append({'id': i.id, 'age': age}) if allUsersAge: for i in range(200): arr = [x['age'] for x in allUsersAge if x['age'] == i] allUsersAgeFiltered.append({'age': i, 'total': len(arr)}) allUsersAgeFilteredSorted = sorted(allUsersAgeFiltered, key=itemgetter('total'), reverse=True) allUsersAgeFiltered = [ i for i in allUsersAgeFiltered if not (i['total'] == 0) ] if allUsersAgeFilteredSorted: # df = pd.DataFrame(allUsersAge) df = pd.DataFrame(allUsersAgeFilteredSorted[:5]) circleDiagram = px.pie( data_frame=df, values='total', #размер куска круга names='age', color='age', ) circleDiagram = circleDiagram.to_html() else: circleDiagram = 'no data to analise yet' if allUsersAgeFiltered: df = pd.DataFrame(allUsersAgeFiltered) fig = px.bar(df, x='age', y='total') fig.update_xaxes(type='category') fig = fig.to_html() else: allUsersAgeFilteredSorted = 'no data to analise yet' circleDiagram = 'no data to analise yet' fig = 'no data to analise yet' # # allUsersInCountries = UserData.objects.values('country_title').annotate(total = Count('country_title')) # # df = pd.DataFrame(allUsersInCountries) # fig1 = px.scatter_geo(df, locations="country_title",hover_name="country_title", size="total",projection="natural earth") # fig1 = fig1.to_html() return render( request, 'visualisationAge.html', { 'circleDiagram': circleDiagram, 'allUsersAgeFilteredSorted': allUsersAgeFilteredSorted, 'fig': fig, })
sentiment_count = pd.DataFrame({ 'Sentiment': sentiment_count.index, 'Tweets': sentiment_count.values }) if not st.sidebar.checkbox("Hide", True): st.markdown("### Number of tweets by sentiment") if select == "Histogram": fig = px.bar(sentiment_count, x='Sentiment', y='Tweets', color='Tweets', height=500) st.plotly_chart(fig) else: fig = px.pie(sentiment_count, values='Tweets', names='Sentiment') st.plotly_chart(fig) st.sidebar.subheader("When and Where are users tweeting from?") hour = st.sidebar.slider("Hour of day", 0, 23) modified_data = data[data['tweet_created'].dt.hour == hour] if not st.sidebar.checkbox("Close", True, key='1'): st.markdown("### Tweet location based on the time of the day") st.markdown("%i tweets %i:00 and %i:00" % (len(modified_data), hour, (hour + 1) % 24)) st.map(modified_data) if st.sidebar.checkbox("Show raw data", False): st.write(modified_data) st.sidebar.subheader("Breakdown airline tweets by sentiment") choice = st.sidebar.multiselect('Pickk airline',
# Data Exploration with Pandas (python) # ----------------------------------------------------------------- df = pd.read_csv("vgsales.csv") print(df[:5]) print(df.iloc[:5, [2, 3, 5, 10]]) print(df.Genre.nunique()) print(df.Genre.unique()) print(sorted(df.Year.unique())) # Data Visualization with Plotly (Python) # ----------------------------------------------------------------- fig_pie = px.pie(data_frame=df, names='Genre', values='Japan Sales') fig_pie = px.pie(data_frame=df, names='Genre', values='North American Sales') fig_pie.show() fig_hist = px.histogram(data_frame=df, x='Genre', y='Japan Sales') fig_hist = px.histogram(data_frame=df, x='Year', y='Japan Sales') fig_hist.show() df = df.groupby(['Year', 'Genre']).sum() df = df.reset_index() print(df[-5:]) fig_bar = px.bar(data_frame=df, x='Year', y='Japan Sales', facet_col='Genre',
#plotting the data from the result dataframe #convert to plotly #making a stacked bar graph fig = go.Figure(data=[ go.Bar(name="Confirmed", x=plt1['Country/Region'], y=plt1['Confirmed']), go.Bar(name='Recovered', x=plt1['Country/Region'], y=plt1['Recovered']), go.Bar(name='Deaths', x=plt1['Country/Region'], y=plt1['Deaths']) ]) fig.update_layout(barmode='group', xaxis_tickangle=-45, title_text='Country Wise Data') #fig.show() #Pie chart fig = px.pie(data_frame=plt1, names='Country/Region', values='Confirmed', title='Country Wise Confirmed') #fig.show() fig = px.pie(data_frame=plt1, names='Country/Region', values='Recovered', title='Country Wise Recovered') #fig.show() fig = px.pie(data_frame=plt1, names='Country/Region', values='Deaths', title='Country Wise Deaths') #fig.show() print("PLOT DATA \n", plt1.head()) #plotting the confirmed cases in an ineractive worldmap
def plot_pie(df): return px.pie(df, values=df.mean(axis=0), names=df.columns)
def display_header_exporter_rapport_pdf(): st.markdown(f"<div id='linkto_ExporterRapportPDF'></div>", unsafe_allow_html=True) figs = [] df = pd.read_csv("UtilisateursVoyey.csv", index_col=0, parse_dates=True) list_of_status = df['VoyeyAkaz\xa0status'].to_list() #print(list_of_status) Data = Counter(list_of_status) #print() Status = ['Actif', 'Inactive'] my_list = [] for i in Status: Number = (Data[i]) my_list.append(Number) #print(my_list) #print() report_text = "Il y a " + str(my_list[1]) + " Inscrits et " + str( my_list[0]) + " abonnés" #a=st.markdown ("Il y a **"+str(my_list[1])+ "** Inscrits et **"+str(my_list[0])+"** abonnés") #figs.append(a) #b=st.markdown ("**Qui sont les nouveaux clients du jours?**") #figs.append(b) CompteCree = df['Compte\xa0créé\xa0le'].to_list() today = datetime.today().date() #print(today) The_list = [] for i in CompteCree: Compte = datetime.strptime(i, "%d/%m/%Y").date() #print(Compte) Newclients = today - Compte Newclients = Newclients.days The_list.append(Newclients) Prenom = df['Prénom'] P = [] for i, j in zip(The_list, Prenom): if i == 0 or i == 1: P.append(j) Nom = df['Nom'] N = [] for i, j in zip(The_list, Nom): if i == 0 or i == 1: N.append(j) Pays = df['Pays'] Pays1 = [] for i, j in zip(The_list, Pays): if i == 0 or i == 1: Pays1.append(j) Email = df['E-mail'] E = [] for i, j in zip(The_list, Email): if i == 0 or i == 1: E.append(j) Statut = df['Statut'] S = [] for i, j in zip(The_list, Statut): if i == 0 or i == 1: S.append(j) C = [] for i, j in zip(The_list, CompteCree): if i == 0 or i == 1: C.append(j) Abonnement = df['VoyeyAkaz\xa0status'].to_list() A = [] for i, j in zip(The_list, Abonnement): if i == 0 or i == 1: A.append(j) Data1 = len(C) ##Pour le nombre d'inscrits dans la semaine C1 = [] for i, j in zip(The_list, CompteCree): if i <= 7: C1.append(j) Data2 = len(C1) ##Pour le nombre d'inscrits dans le mois C2 = [] for i, j in zip(The_list, CompteCree): if i <= 30: C2.append(j) Data3 = len(C2) report_text1 = "Il y a eu +" + str( Data1) + " nouveaux inscrits entre hier et aujourd'hui" report_text2 = "Il y a eu +" + str( Data2) + " nouveaux inscrits au cours des 7 derniers jours" report_text3 = "Il y a eu +" + str( Data3) + " nouveaux inscrits au cours des 30 derniers jours" fig = go.Figure(data=[ go.Table(header=dict(values=[ 'Prénom', 'Nom', 'Pays', 'Email', 'Statut', 'Compte Crée', 'Abonnement' ]), cells=dict(values=[P, N, Pays1, E, S, C, A])) ]) fig.update_layout(height=600, width=600, title_text="Nouveaux inscrits entre hier et aujourd'hui") figs.append(fig) df = pd.read_csv("UtilisateursVoyey.csv", index_col=0, parse_dates=True) df.fillna('01/01/2200', inplace=True) #print(df) my_data = pd.read_csv("UtilisateursVoyey.csv", sep=',', header=0, usecols=[0]) #print(my_data) list_of_actif = my_data['Voyey\xa0ID'].to_list() #print(list_of_actif) Data = Counter(list_of_actif) #print(Data) today = datetime.today().date() Startdate = df['Start\xa0date'].to_list() #print(Startdate) Abonne_list = [] for i in Startdate: Compte = datetime.strptime(i, "%d/%m/%Y").date() #print(Compte) Newclients = today - Compte Newclients = Newclients.days Abonne_list.append(Newclients) PrenomAbonne = df['Prénom'] PA = [] for i, j in zip(Abonne_list, PrenomAbonne): if 0 < i <= 7: PA.append(j) NomAbonne = df['Nom'] NA = [] for i, j in zip(Abonne_list, NomAbonne): if 0 < i <= 7: NA.append(j) PaysAbonne = df['Pays'] PaysA = [] for i, j in zip(Abonne_list, PaysAbonne): if 0 < i <= 7: PaysA.append(j) EmailAbonne = df['E-mail'] EA = [] for i, j in zip(Abonne_list, EmailAbonne): if 0 < i <= 7: EA.append(j) #print(EA) Start = df['Start\xa0date'] SA = [] for i, j in zip(Abonne_list, Start): if 0 < i <= 7: SA.append(j) End = df['End\xa0date'] EnA = [] for i, j in zip(Abonne_list, End): if 0 < i <= 7: EnA.append(j) D = [] for i, j in zip(Abonne_list, Startdate): if i == 1: D.append(j) Data = len(D) ##Pour le nombre d'abonnés dans la semaine D1 = [] for i, j in zip(Abonne_list, Startdate): if 0 < i <= 7: D1.append(j) Data4 = len(D1) ##Pour le nombre d'abonnés dans le mois D2 = [] for i, j in zip(Abonne_list, Startdate): if 0 < i <= 30: D2.append(j) Data5 = len(D2) #print(Data5) Datededebut = df['Start\xa0date'].to_list() Datedefin = df['End\xa0date'].to_list() Datededebut = [str(x) for x in Datededebut] Datededebut = [x for x in Datededebut if x != 'nan'] Datedefin = [str(x) for x in Datedefin] Datedefin = [x for x in Datedefin if x != 'nan'] def days_between(d1, d2): d1 = datetime.strptime(d1, "%d/%m/%Y") d2 = datetime.strptime(d2, "%d/%m/%Y") return abs((d2 - d1).days) my_list = [] for i, j in zip(Datededebut, Datedefin): c = days_between(i, j) my_list.append(c) #my_list = [0 if x<32 else 1 for x in my_list] #print(my_list) my_list = ["Mensuel" if 0 < x < 32 else "Annuel" for x in my_list] #print(my_list) TypeA = [] for i, j in zip(Abonne_list, my_list): if 0 < i <= 7: TypeA.append(j) report_text4 = ("**Qui sont les nouveaux abonnés du jours?**") report_text5 = ("Il y a eu +" + str(Data) + " nouveaux abonnés entre hier et aujourd'hui") report_text6 = ("Il y a eu +" + str(Data4) + " nouveaux abonnés au cours des 7 derniers jours") report_text7 = ("Il y a eu +" + str(Data5) + " nouveaux abonnés au cours des 30 derniers jours") figure1 = go.Figure(data=[ go.Table(header=dict(values=[ 'Prénom', 'Nom', 'Pays', 'Email', 'Debut Abonnement', 'Fin Abonnement', 'Type Abonnement' ]), cells=dict(values=[PA, NA, PaysA, EA, SA, EnA, TypeA])) ]) figure1.update_layout(height=600, width=600, title_text="Les Nouveaux abonnés de la semaine") figs.append(figure1) #################################################### #st.plotly_chart(figure) list_of_island = df['Pays'].to_list() Data = Counter(list_of_island) #print(Data) Island = [ 'Guadeloupe', 'Martinique', 'Guyane française', 'La Réunion', 'France', 'NA', 'Canada' ] # Here green is not in col_count # so count of green will be zero my_list = [] for i in Island: Number = (Data[i]) my_list.append(Number) fig = px.pie(df, values=my_list, names=Island, title='Nombres de personnes inscrites par iles') #st.plotly_chart(fig) figs.append(fig) ######################################################### list_of_status = df['Titre'].to_list() Data = Counter(list_of_status) Status = ['Monsieur', 'Madame', '-'] my_list = [] for i in Status: Number = (Data[i]) my_list.append(Number) fig = px.pie(df, values=my_list, names=Status, title='Sexe des individus inscrits') figs.append(fig) ################################################################################ birthDate = df['Date\xa0de\xa0naissance'].to_list() currentDate = datetime.today().date() #print(currentDate) #print(birthDate) M_list = [] for i in birthDate: if i == '-': continue birthDate = datetime.strptime(i, "%d/%m/%Y").date() age = currentDate.year - birthDate.year age = int(age) M_list.append(age) df1 = pd.DataFrame(M_list, columns=['Age']) print(df1) df1['Age_groupe'] = pd.cut( df1.Age, bins=[0, 18, 25, 30, 40, 50, 60, 80, 100, 10000], labels=[ '0-18', '18-25', '25-30', '30-40', '40-50', '50-60', '60-80', '80-100', '100-1000' ]) print(df1) list_of_bins = df1['Age_groupe'].to_list() print(list_of_bins) Data = Counter(list_of_bins) print(Data) Ages = [ '0-18', '18-25', '25-30', '30-40', '40-50', '50-60', '60-80', '80-100', '100-1000' ] The_list = [] for i in Ages: Number = (Data[i]) The_list.append(Number) print(The_list) fig = px.pie(df1, values=The_list, names=Ages, title='Ages des clients') figs.append(fig) ################################################################################ list_of_status = df['Statut'].to_list() Data = Counter(list_of_status) Status = ['Active', 'Inactive'] my_list = [] for i in Status: Number = (Data[i]) my_list.append(Number) fig = px.pie(df, values=my_list, names=Status, title='Status de la validité du compte') figs.append(fig) emails = df['E-mail'] Email = [] for i, e in enumerate(list_of_status): if e == 'Inactive': e = emails[i] print(e) Email.append(e) Noms = df['Nom'] N = [] for i, e in enumerate(list_of_status): if e == 'Inactive': e = Noms[i] print(e) N.append(e) Prénom = df['Prénom'] P = [] for i, e in enumerate(list_of_status): if e == 'Inactive': e = Prénom[i] print(e) P.append(e) S = ['Inactive'] list = [] for i in S: Number = (Data[i]) list.append(Number) e = list[0] e = int(e) fig = go.Figure(data=[ go.Table(header=dict(values=['Prénom', 'Nom', 'Email', 'Status']), cells=dict(values=[P, N, Email, S * e])) ]) fig.update_layout( height=600, width=600, title_text="Tableau des personnes ayant oubliés de valider leur compte:" ) figs.append(fig) ######################################################################## Datededebut = df['Start\xa0date'].to_list() Datedefin = df['End\xa0date'].to_list() Datededebut = [str(x) for x in Datededebut] Datededebut = [x for x in Datededebut if x != 'nan'] Datedefin = [str(x) for x in Datedefin] Datedefin = [x for x in Datedefin if x != 'nan'] def days_between(d1, d2): d1 = datetime.strptime(d1, "%d/%m/%Y") d2 = datetime.strptime(d2, "%d/%m/%Y") return abs((d2 - d1).days) my_list = [] for i, j in zip(Datededebut, Datedefin): c = days_between(i, j) my_list.append(c) #my_list = [0 if x<32 else 1 for x in my_list] my_list = ["Mensuel" if x < 32 else "Annuel" for x in my_list] Data = Counter(my_list) Status = ['Mensuel', 'Annuel'] M_list = [] for i in Status: Number = (Data[i]) M_list.append(Number) fig = px.pie( df, values=M_list, names=Status, title='Représentation des types Abonnements choisis par nos abonnés') figs.append(fig) #st.plotly_chart(fig) Mensuel = M_list[0] Mensuel = int(Mensuel) * 9.99 Annuel = M_list[1] Annuel = int(Annuel) * 49 CATotal = int(Mensuel + Annuel) #st.markdown ("Chiffre d'affaire sur les abonnements mensuels: **"+str(Mensuel)+"€** et annuels: **"+str(Annuel)+"€**" ) #st.markdown ("Chiffre d'affaire total: **"+str(CATotal)+"€**") #st.markdown ("Qui sont nos abonné(e)s?") list_of_status = df['VoyeyAkaz\xa0status'].to_list() emails = df['E-mail'] Email = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = emails[i] print(e) Email.append(e) Noms = df['Nom'] N = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = Noms[i] print(e) N.append(e) Prénom = df['Prénom'] P = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = Prénom[i] print(e) P.append(e) list_of_status = df['VoyeyAkaz\xa0status'].to_list() Island = df['Pays'] Island_list = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = Island[i] Island_list.append(e) list_of_status = df['VoyeyAkaz\xa0status'].to_list() Start = df['Start\xa0date'].to_list() Start_list = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = Start[i] Start_list.append(e) End = df['End\xa0date'].to_list() End_list = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = End[i] End_list.append(e) Data = Counter(list_of_status) S = ['Actif'] list = [] for i in S: Number = (Data[i]) list.append(Number) e = list[0] e = int(e) fig = go.Figure(data=[ go.Table(header=dict(values=[ 'Prénom', 'Nom', 'Email', 'Iles', 'Abonnement', 'Start', 'End' ]), cells=dict(values=[ P, N, Email, Island_list, my_list, Start_list, End_list ])) ]) #st.plotly_chart(figure) fig.update_layout(height=600, width=600, title_text="Nos actuels abonnés") figs.append(fig) ################################################################################ df = pd.read_csv("UtilisateursVoyey.csv", index_col=0, parse_dates=True) list_of_status = df['VoyeyAkaz\xa0status'].to_list() today = datetime.today().date() End = df['End\xa0date'].to_list() End_list = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = End[i] End_list.append(e) #print (End_list) The_list = [] for i in End_list: Compte = datetime.strptime(i, "%d/%m/%Y").date() #print(Compte) Newclients = Compte - today Newclients = Newclients.days The_list.append(Newclients) End = [] for i, j in zip(The_list, End_list): if i <= 7: End.append(j) Prenom = df['Prénom'] P = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = Prenom[i] P.append(e) #print(P) P1 = [] for i, j in zip(The_list, P): if i <= 7: P1.append(j) #print(P1) Nom = df['Nom'] N = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = Nom[i] N.append(e) N1 = [] for i, j in zip(The_list, N): if i <= 7: N1.append(j) #print(N1) Nom = df['Nom'] N = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = Nom[i] N.append(e) N1 = [] for i, j in zip(The_list, N): if i <= 7: N1.append(j) Email = df['E-mail'] EM = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = Email[i] EM.append(e) EM1 = [] for i, j in zip(The_list, EM): if i <= 7: EM1.append(j) Pays = df['Pays'] Pays1 = [] for i, e in enumerate(list_of_status): if e == 'Actif': e = Pays[i] Pays1.append(e) Pays2 = [] for i, j in zip(The_list, Pays1): if i <= 7: Pays2.append(j) #print(Pays2) Datededebut = df['Start\xa0date'].to_list() Datedefin = df['End\xa0date'].to_list() Datededebut = [str(x) for x in Datededebut] Datededebut = [x for x in Datededebut if x != 'nan'] Datedefin = [str(x) for x in Datedefin] Datedefin = [x for x in Datedefin if x != 'nan'] def days_between(d1, d2): d1 = datetime.strptime(d1, "%d/%m/%Y") d2 = datetime.strptime(d2, "%d/%m/%Y") return abs((d2 - d1).days) my_list = [] for i, j in zip(Datededebut, Datedefin): c = days_between(i, j) my_list.append(c) #my_list = [0 if x<32 else 1 for x in my_list] my_list = ["Mensuel" if x < 32 else "Annuel" for x in my_list] Type_abonnement = [] for i, j in zip(The_list, my_list): if i <= 7: Type_abonnement.append(j) #st.markdown ("Voici les abonnements se terminant dans la semaine") fig = go.Figure(data=[ go.Table(header=dict( values=['Prénom', 'Nom', 'Email', 'Iles', 'Abonnement', 'End']), cells=dict(values=[P1, N1, EM1, Pays2, Type_abonnement, End])) ]) fig.update_layout( height=600, width=600, title_text="Voici les abonnements se terminant dans la semaine") figs.append(fig) #st.markdown ("D'ou viennent nos abonnés?") list_of_status = df['VoyeyAkaz\xa0status'].to_list() list_of_island = df['Pays'].to_list() #print(list_of_status) Data1 = Counter(list_of_island) #print(list_of_island) Data1 = Counter(list_of_status) print(Data) Island = [ 'Guadeloupe', 'Martinique', 'Guyane française', 'La Réunion', 'France', 'NA', 'Canada' ] # Here green is not in col_count # so count of green will be zero The_list = [] I = [] for i, e in enumerate(list_of_status): if e == 'Actif': Number = (list_of_island[i]) The_list.append(Number) print(The_list) Data = Counter(The_list) my_list = [] for i in Island: Number = (Data[i]) my_list.append(Number) fig = px.pie(df, values=my_list, names=Island, title='Représentations des abonné(e)s par iles') #st.plotly_chart(fi) figs.append(fig) ####################################################### list_of_status = df['VoyeyAkaz\xa0status'].to_list() #print(list_of_status) Data = Counter(list_of_status) #print() Status = ['Actif', 'Inactive'] my_list = [] for i in Status: Number = (Data[i]) my_list.append(Number) fig = px.pie(df, values=my_list, names=Status, title='Pourcentage des abonnés par rapport aux inscrits') figs.append(fig) ##################################################### export_as_pdf = st.button("Export Report") def create_download_link(val, filename): b64 = base64.b64encode(val) # val looks like b'...' return f'<a href="data:application/octet-stream;base64,{b64.decode()}" download="{filename}.pdf">Download file</a>' if export_as_pdf: pdf = FPDF() pdf.add_page() pdf.set_font('Arial', 'B', 16) pdf.cell(40, 20, report_text, 0, 1) pdf.cell(40, 20, report_text1, 0, 1) pdf.cell(40, 20, report_text2, 0, 1) pdf.cell(40, 20, report_text3, 0, 1) pdf.cell(40, 20, report_text4, 0, 1) pdf.cell(40, 20, report_text5, 0, 1) pdf.cell(40, 20, report_text6, 0, 1) pdf.cell(40, 20, report_text7, 0, 1) for fig in figs: pdf.add_page() with NamedTemporaryFile(delete=False, suffix=".png") as tmpfile: fig.write_image(tmpfile.name) pdf.image(tmpfile.name, 10, 10, 200, 100) html = create_download_link( pdf.output(dest="S").encode("latin-1"), "testfile") st.markdown(html, unsafe_allow_html=True) return None
autosize=False, width=640, height=230, margin=dict( l=10, r=10, b=10, t=10, pad=4 ), paper_bgcolor="LightSteelBlue",) fig_cpu.write_html("static/cpu_chart.html") fig_disk = px.pie(disk,values='datos', names='Estado', title='Espacio en disco', color='Estado', color_discrete_map={'Usado':'royalblue', 'Libre':'lightgreen'}) fig_disk.update_layout( autosize=False, width=230, height=230, margin=dict( l=5, r=10, b=1, t=30, pad=4 ), paper_bgcolor="LightSteelBlue",) fig_disk.write_html("static/disk_pie.html")
) map.update_geos( visible=False, showcountries=True, countrycolor="#fb7813", showocean=True, oceancolor="#414141", ) # PIE df = px.data.tips() pie = px.pie(df, values='tip', names='day', color='day', color_discrete_map={ 'Thur': 'lightcyan', 'Fri': 'cyan', 'Sat': 'royalblue', 'Sun': 'darkblue' }) pie.update_layout(plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)', legend=dict(font=dict(family="sans-serif", size=18, color="#ca3e47"), )) # line import numpy as np x = np.arange(10)
# pie_figure.write_image("pie_figure.png") # photo_path = open('pie_figure.png', 'rb') ################# End of Data Processing for Risky Client Information ######################### app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) # msg_id = send_msg(chat_id, msg_text) # r = requests.post(base_url + 'sendPhoto', data={'chat_id': chat_id}, files={'photo': photo_path}) # print(r.status_code) app.layout = html.Div([ dbc.Row([ # This is Overall Current Risk Profiles Breakdown Piechart dbc.Col([dcc.Graph(id='current_risk_piechart', figure = px.pie(risk_analysis_df, values='Count', names='Current Risk Level', title='Overall Current Risk Profiles Breakdown' ).update_traces(textposition='inside', textinfo='percent+label').update_layout(legend_title="Current Risk Level") )], width={'size':3},), # This is Target Status Breakdown Piechart dbc.Col([dcc.Graph(id='target_status_piechart', figure = px.pie(risk_analysis_df, values='Count', names='Target Status', title='Target Status Breakdown' ).update_traces(textposition='inside', textinfo='percent+label') )], width={'size':3},), # This is Filter + Table dbc.Col([ # This is Target Risk Level Filter for the Table below dcc.Dropdown( id='target_risk_filter',
color='Confirmed', color_continuous_scale='Purp', hover_name='State', hover_data={'State_spaced': False, 'Confirmed': False} ) fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide', title=f'COVID-19 Malaysia: Total Cases as of {last_date}', width=700, height=800, xaxis_title=None, yaxis_title=None, showlegend=False, coloraxis_showscale=False) fig.update_traces(texttemplate='%{text:,}') st.plotly_chart(fig, use_container_width=True) fig = px.pie(df_state_total, values='Confirmed', names='State', height=600, hover_name='State', hover_data={'State': False} ) fig.update_traces(textposition='inside', textinfo='percent+label') fig.update_layout( title=f'COVID-19 Malaysia: Proportion of Confirmed Cases as of {last_date}', # title_x=0.1 ) st.plotly_chart(fig, use_container_width=True) def plot_choropleth(df): fig = px.choropleth( df,
def get_graph(chart, year, children1, children2, c3, c4, c5): # Select data df = airline_data[airline_data['Year'] == (year)] if chart == 'OPT1': # Compute required information for creating graph from the data bar_data, line_data, div_data, map_data, tree_data = compute_data_choice_1( df) # Number of flights under different cancellation categories bar_fig = px.bar(bar_data, x='Month', y='Flights', color='CancellationCode', title='Monthly Flight Cancellation') # TODO5: Average flight time by reporting airline line_fig = px.line( line_data, x='Month', y='AirTime', color='Reporting_Airline', title='Average monthly flight time (minutes) by airline') # Percentage of diverted airport landings per reporting airline pie_fig = px.pie(div_data, values='Flights', names='Reporting_Airline', title='% of flights by reporting airline') # REVIEW5: Number of flights flying from each state using choropleth map_fig = px.choropleth( map_data, # Input data locations='OriginState', color='Flights', hover_data=['OriginState', 'Flights'], locationmode='USA-states', # Set to plot as US States color_continuous_scale='GnBu', range_color=[0, map_data['Flights'].max()]) map_fig.update_layout( title_text='Number of flights from origin state', geo_scope='usa') # Plot only the USA instead of globe # TODO6: Number of flights flying to each state from each reporting airline tree_fig = px.treemap( tree_data, path=['DestState', 'Reporting_Airline'], values='Flights', color='Flights', color_continuous_scale='RdBu', title='Flight count by airline to destination state') # REVIEW6: Return dcc.Graph component to the empty division return [ dcc.Graph(figure=tree_fig), dcc.Graph(figure=pie_fig), dcc.Graph(figure=map_fig), dcc.Graph(figure=bar_fig), dcc.Graph(figure=line_fig) ] else: # REVIEW7: This covers chart type 2 and we have completed this exercise under Flight Delay Time Statistics Dashboard section # Compute required information for creating graph from the data avg_car, avg_weather, avg_NAS, avg_sec, avg_late = compute_data_choice_2( df) # Create graph carrier_fig = px.line( avg_car, x='Month', y='CarrierDelay', color='Reporting_Airline', title='Average carrrier delay time (minutes) by airline') weather_fig = px.line( avg_weather, x='Month', y='WeatherDelay', color='Reporting_Airline', title='Average weather delay time (minutes) by airline') nas_fig = px.line(avg_NAS, x='Month', y='NASDelay', color='Reporting_Airline', title='Average NAS delay time (minutes) by airline') sec_fig = px.line( avg_sec, x='Month', y='SecurityDelay', color='Reporting_Airline', title='Average security delay time (minutes) by airline') late_fig = px.line( avg_late, x='Month', y='LateAircraftDelay', color='Reporting_Airline', title='Average late aircraft delay time (minutes) by airline') return [ dcc.Graph(figure=carrier_fig), dcc.Graph(figure=weather_fig), dcc.Graph(figure=nas_fig), dcc.Graph(figure=sec_fig), dcc.Graph(figure=late_fig) ]
def generate_chart(names, datatype): fig = px.pie(showGenre(names, datatype), values='count', names=datatype) return fig
sentiment_count = pd.DataFrame({ 'Sentiment': sentiment_count.index, 'Tweets': sentiment_count.values }) #move to plotting if not stml.sidebar.checkbox("Hide", True): #by defualt hide the checkbar stml.markdown("### Number of tweets by sentiment") if select == 'Bar plot': fig = px.bar(sentiment_count, x='Sentiment', y='Tweets', color='Tweets', height=500) stml.plotly_chart(fig) else: fig = px.pie(sentiment_count, values='Tweets', names='Sentiment') stml.plotly_chart(fig) #by Time and places stml.sidebar.subheader("Time and location of tweets") hour = stml.sidebar.slider("Hour to look at", 0, 23) modified_data = data[data['tweet_created'].dt.hour == hour] if not stml.sidebar.checkbox("Close", True, key='1'): stml.markdown("### Tweet locations based on time of the day") stml.markdown("%i tweets between %i:00 and %i:00" % (len(modified_data), hour, (hour + 1) % 24)) stml.map(modified_data) if stml.sidebar.checkbox("Show raw data", False): stml.write(modified_data) #Interactive bar plots