def gen_report(file_path): comps = ['腾讯', '阿里', '百度', '京东', '美团', '小米', '字节跳动', '滴滴'] df_dict = pd.read_excel(file_path, comps) for k, v in df_dict.items(): v['投资主体'] = k # domain_set = set().union(* [set(df['行业']) for df in df_dict.values()]) # df_all = pd.concat(df_dict.values()) df_all = pd.concat(df_dict) df_all['海外'] = df_all['海外'].where(df_all['海外'].notnull(), '国内') fig = px.treemap(df_all, path=['行业', '投资主体', '日期', '公司简称']) fig.show()
def variable_directory(): """ this plots the directory map of all variables in the code base """ # TODO: put it into the right data frame var_id = [] var_alias = [] scheme_name = [] method_name = [] file_name = [] # file_var_count = [] for entry in Variable.objects.all(): var_id.append(entry.name) var_alias.append(entry.metadata['alias']) directory_list = entry.directory.split("/") if (directory_list[0] == 'variables'): scheme_name.append(directory_list[1]) if (directory_list[-1].endswith('.py')): file_name.append(directory_list[-1]) if (len(directory_list) == 4): method_name.append(directory_list[2]) else: method_name.append(directory_list[-1].split(".py")[0]) df_var = pd.DataFrame(data={ 'var_id': var_id, 'alias': var_alias, 'scheme': scheme_name, 'method': method_name, 'file': file_name, }) df_var.reset_index() # file_counts = df_var['file'].value_counts() # df1 = df_var.groupby(by='method').agg('count') fig = px.treemap( df_var, path=['scheme', 'method', 'file'], color='scheme', color_discrete_map={ '(?)': colorScheme['highlight_color'], 'General_Appliances': colorScheme['trace2_color'], 'Home_Energy_Efficiency_Retrofits (HEER)': colorScheme['trace2_color'], 'High_Efficiency_Appliances_Business (HEAB)': colorScheme['trace2_color'], 'Other_ESS_methods': colorScheme['trace1_color'], 'Removal_of_Old_Appliances (RoOA)': colorScheme['trace2_color']}, title="Overview of Openfisca_nsw_safeguard Code Base", height=700, width=1500) fig.update_layout(uniformtext=dict(minsize=14, mode='hide')) plot_div = fig.to_html(full_html=False) return plot_div
def position_company_treemap(connections_df): #connections_df = connections_df.dropna(subset=['Position', 'Company']) connections_df['Company'] = connections_df['Company'].fillna("Other") connections_df['Position'] = connections_df['Position'].fillna("Other") connections_df["PositionCount"] = 1 connections_df["Name"] = connections_df["First Name"] + " " + connections_df["Last Name"] fig = px.treemap(connections_df, path=['Position', "Company", "Name"], values="PositionCount", ) fig.update_layout(title='Job positions of your connected people for each company') return fig
def covid_16(): fig = px.treemap(e_lat_grp.sort_values( by='Cases', ascending=False).reset_index(drop=True), path=["Country"], values="Cases", title='EBOLA', color_discrete_sequence=px.colors.qualitative.Dark2) fig.data[0].textinfo = 'label+text+value' #fig.show() plotly.offline.plot(fig, filename="choro", image='svg', auto_open=True) return render_template("Vizualize.html")
def treemap(data): return px.treemap( data, names=data["Short Callpath"], parents=data["Parent"], values=data["Time (Inclusive)"], color=data["Time Imbalance"], branchvalues="total", ) import dash
def treemap_1(attribute): plotdata = rawdata.sort_values('Tesla') fig = px.treemap(plotdata, path=[str(attribute), 'Manufacturer'], color='Tesla', hover_data=['Manufacturer', attribute], color_discrete_sequence=[color1, color6], height=800, title=('Category:{}').format(attribute)) return\ fig
def treemap_2(attribute='value'): plotdata = rawdata.sort_values('Range') fig = px.treemap(plotdata, path=[attribute, 'Manufacturer'], color='Range', hover_data=['Manufacturer', attribute], color_continuous_scale=[color1, color3], title=('Category:{}').format(attribute), height=800) #.update(layout_showlegend=False) return\ fig#.update(showlegend=False)
def covid_21(): fig = px.treemap(s_lat_grp.sort_values( by='Deaths', ascending=False).reset_index(drop=True), path=["Country"], values="Deaths", title='SARS', color_discrete_sequence=px.colors.qualitative.Dark2) fig.data[0].textinfo = 'label+text+value' #fig.show() fig.write_html("templates/choro21.html") return render_template("choro21.html")
def company_position_treemap(connections_df): #connections_df = connections_df.dropna(subset=['Position', 'Company']) connections_df['Company'] = connections_df['Company'].fillna("Other") connections_df['Position'] = connections_df['Position'].fillna("Other") connections_df["PositionCount"] = 1 connections_df["Name"] = connections_df["First Name"] + " " + connections_df["Last Name"] fig = px.treemap(connections_df, path=['Company', 'Position', 'Name'], values="PositionCount", ) fig.update_layout(title='Companies where your connected people work for each job position') return fig
def gen_report_all(file_path): df = pd.read_excel(file_path) # 转时间序列 df['日期'] = pd.to_datetime(df['日期']) df = df.set_index('日期').to_period('A') df['日期'] = df.index # print(df) fig = px.treemap(df, path=['行业', '投资主体', '日期', '公司简称']) fig.write_html(str(file_path.parent.joinpath('all.html'))) fig.write_image(str(file_path.parent.joinpath('all.png')), scale=20) fig.show()
def single_graph_tree(feature): title = 'Trade Performance of Malaysia based on {} from 2013 to 2019'.format( feature) if feature == 'COUNTRY': df_group = df.groupby('COUNTRY')[show].sum().reset_index() df_merge = df_group.merge(df_country, on='COUNTRY', how='inner') df_merge = df_merge[df_merge[show] > 0] df_merge["WORLD"] = "WORLD" fig = px.treemap(df_merge, path=['WORLD', 'Region', feature], values=show, color=show, hover_data=[show], color_continuous_scale='RdBu', title=title) fig.update_layout(height=600, width=900) st.plotly_chart(fig) elif feature == 'SITC 2 DIGIT': df_merge = df.groupby([feature, 'SITC 1 DIGIT'])[show].sum().reset_index() df_merge = df_merge[df_merge[show] > 0] df_merge["COMMODITY"] = "COMMODITY" fig = px.treemap(df_merge, path=['COMMODITY', 'SITC 1 DIGIT', feature], values=show, color=show, hover_data=[show], color_continuous_scale='RdBu', title=title) fig.update_layout(height=600, width=900) st.plotly_chart(fig) else: fig = px.treemap(df, path=[feature], values=show, color=show, hover_data=[show], color_continuous_scale='RdBu', title=title) fig.update_layout(height=600, width=900) st.plotly_chart(fig)
def makeChart(colorWithCats, name): df = pd.DataFrame(colorWithCats) # columns=cols) print(df) fig = px.treemap(df, path=df.columns[-1:0:-1], values=0, color=0, color_continuous_scale=getColorScale(name), color_continuous_midpoint=df[0].mean(), title='Nouns and their WordNet categories commonly associated with the adjective ' + name ) with open(name+'.html', 'w') as f: f.write(fig.to_html())
def print_treemap(dataframe): figure = px.treemap( dataframe.dropna(), path=['Province', 'naics_sect', 'Funding_Program_Name'], values='$_Amount', color='$_Amount', color_continuous_scale='Oranges', #hover_data={'$_Amount': True} # This statement doesnt work -DFL # perhaps can turn off hover in general, and display $_Amount as text instead # width=400, ) return figure
def generateCountryInfectionTreemap(): sample = covid_data.rename(columns={ "location": "Kraj", "num_sequences_total": "Liczba przypadków" }) fig = px.treemap( sample, path=[px.Constant('Liczba przypadków'), 'Kraj'], values='Liczba przypadków', hover_data=['Kraj'], ) fig.show()
def BTGpactual_printTreemap(df, bins): # Simple treemap fig1 = px.treemap(df, path=["Ação"], values="Taxa %", color="Ação") fig1.show() # Elaborate treemap df99 = BTGpactual_get99percentileDF(df) # Create categories min_value = df99["Taxa %"].min() max_value = df99["Taxa %"].max() bin_interval = (max_value - min_value) / bins ranges = [bin_interval * i for i in range(bins + 2)] group_names = ["Group" + str(i + 1) for i in range(bins + 1)] # Prepare treemap df99["Group"] = pd.cut(df99["Taxa %"], bins=ranges, labels=group_names) df99["BTC"] = "BTC" # In order to have a single root node fig = px.treemap(df99, path=["BTC", "Group", "Ação"], values="Taxa %", color="Ação") fig.show()
def simpletreemap(): dataset = pd.read_csv('Iris.csv') fig = px.treemap(dataset, path=['SepalLengthCm', 'SepalWidthCm', 'Species'], values='PetalWidthCm') graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) header = "Plotting the results" description = """Iris dataset each data point is represented as a marker point.""" return render_template('index.html', graphJSON=graphJSON, header=header, description=description)
def plot_treemap(): data = system_info[system_info['PLN_AREA_N'] != 'NOT SPECIFIED'] fig = px.treemap( data, path=['Country', 'Region', 'PLN_AREA_N', 'System type'], values='System size', color='Region', color_continuous_scale='Reds', hover_data=["PLN_AREA_N"], title='Cumulative installed capacity (kWp) by planning area') fig.show() pio.write_html(fig, file='treemap.html', auto_open=True)
def portfolio_treemap(): tbic_port = get_portfolio_data() tbic_port[ "portfolio"] = "The TBIC Portfolio - Go Bears!! (Click to drill down...)" # tbic_port.to_pickle(cwd.joinpath("assets/sector_tree.pkl")) fig = px.treemap(tbic_port, path=['portfolio', 'Sector', 'Industry', 'Company Name'], values='GBP Value', color='% Gain', color_continuous_scale='thermal') return dcc.Graph(figure=fig)
def undervalued_treemap(): df = si.get_undervalued_large_caps() df['portfolio'] = "Undervalued Large Caps. Trailing P/E < 20, Price/Earnings to Growth < 1" df['MarketCap'] = df['Market Cap'].map(lambda x: x.split("B")[0]).astype( float) df['1d chg'] = df['% Change'].map(lambda x: x.split("%")[0]).astype(float) fig = px.treemap(df, path=['portfolio', 'Name'], values='MarketCap', color='1d chg', color_continuous_scale='thermal') return dcc.Graph(figure=fig)
def projects_treemap_chart(raw_data: PomodorosProcessed): data = raw_data.df.groupby('Activity').agg({ 'Pomodoros': 'sum', 'Parent': 'max' }) fig = px.treemap(data.reset_index(), values='Pomodoros', names='Activity', parents='Parent', color_discrete_sequence=px.colors.qualitative.Pastel + px.colors.qualitative.D3) st.plotly_chart(fig, use_container_width=True)
def currency_treemap(value): tbic_port = get_portfolio_data(value) tbic_port["portfolio"] = "The TBIC Portfolio - By Currency" fig = px.treemap( tbic_port, path=['portfolio', 'CCY', 'Sector', 'Industry', 'Company Name'], values='GBP Value', color='% Gain', color_continuous_scale='thermal', height=700) return fig
def tab4_content(): fig1 = px.treemap( df_cost_rating, path=[px.Constant('All'), 'Rating text', 'Price range text'], values='Price range', title='Price range percentage according to Rating') fig2 = px.scatter(df_cost_rating[[ 'Rating text', 'Price range', 'Aggregate rating' ]].groupby('Rating text').mean().reset_index().sort_values('Price range'), x='Price range', y='Aggregate rating', color='Rating text', title='Rating and Cost Correlation') fig2.update_traces(marker=dict(size=12, line=dict(width=2)), selector=dict(mode='markers')) fig3 = px.scatter(df_cost_rating, x='Aggregate rating', y='Average Cost for two in dollars', color='Aggregate rating', title='Average Cost for two in dollars vs Rating') fig3.update_traces(marker=dict(size=12, ), selector=dict(mode='markers')) return html.Div([ dbc.Card( dbc.CardBody([ html.H4("Restaurants", className="card-title"), html.H6("There is a good partion of Rating unrated", className="card-text"), html.H6("There is correlation between Rating and cost", className="card-text"), html. H6("Restaurants with high price range tend to have good rating", className="card-text"), ]), className="mt-3", ), dbc.Card( dbc.CardBody( [dcc.Graph(id='bar-graph-restaurant-rating', figure=fig1)]), className="mt-3", ), dbc.Card( dbc.CardBody( [dcc.Graph(id='scatter-graph-cost-rating', figure=fig2)]), className="mt-3", ), dbc.Card( dbc.CardBody([dcc.Graph(id='scatter-graph-cost-two', figure=fig3)]), className="mt-3", ), ])
def set_table_data(n_clicks, locations): if not n_clicks: raise PreventUpdate log_loc = trend_locs['name'][locations] logging.info(msg=list(log_loc)) try: woeid = trend_locs['woeid'][locations] df = adv.twitter.get_place_trends(woeid) n_countries = df['country'].nunique() countries = df['country'].unique() fig = make_subplots( rows=n_countries, cols=1, subplot_titles=['Worldwide' if not c else c for c in countries], specs=[[{ 'type': 'treemap' }] for i in range(n_countries)], vertical_spacing=0.05) for i, c in enumerate(countries): sub_fig_df = df[df['country'] == c] sub_fig = px.treemap(sub_fig_df, path=['country', 'location', 'name'], values='tweet_volume') sub_fig.layout.margin = {'b': 5, 't': 5} sub_fig.data[0][ 'hovertemplate'] = '<b>%{label}</b><br>Tweet volume: %{value}' last_line = '' if c == '' else '<br>%{percentRoot} of %{root}' sub_fig.data[0][ 'texttemplate'] = '<b>%{label}</b><br><br>Tweet volume: %{value}<br>%{percentParent} of %{parent}' + last_line fig.add_trace(sub_fig.to_dict()['data'][0], row=i + 1, col=1) fig.layout.height = 400 * n_countries fig.layout.template = 'none' fig.layout.margin = {'t': 40, 'b': 40} fig.layout.paper_bgcolor = '#000000' fig.layout.plot_bgcolor = '#000000' final_df = df.drop(['promoted_content', 'woeid', 'parentid'], axis=1) final_df = final_df.rename(columns={'name': 'Topic'}) final_df.columns = [ x.title() for x in final_df.columns.str.replace('_', ' ') ] url_search = '?q=' + '+'.join(log_loc) return final_df.to_dict('rows'), url_search, fig.to_dict() except Exception as e: return pd.DataFrame( { 'Name': ['Too many requests please ' 'try again in 15 minutes.'] }, columns=df.columns).to_dict('rows')
def covid_13(): global c_lat_grp fig = px.treemap(c_lat_grp.sort_values( by='Deaths', ascending=False).reset_index(drop=True), path=["Country"], values="Deaths", title='COVID-19 Deaths', color_discrete_sequence=px.colors.qualitative.Dark2) fig.data[0].textinfo = 'label+text+value' #fig.show() #fig.savefig(img) #img.seek(0) plotly.offline.plot(fig, filename="choro", image='svg', auto_open=True) return render_template("Vizualize.html")
def graph(): fig = px.treemap( df, path=['state', 'confirmed', 'active', 'recovered'], values='active', color='active', hover_data=['confirmed', 'recovered'], color_continuous_scale='RdBu', color_continuous_midpoint=np.average(df['confirmed'], weights=df['active']), title='Statewise Cases', ) fig.show()
def main(): ''' 生成树状图 ''' df = px.data.gapminder().query("year == 2007") fig = px.treemap(df, path=['continent', 'country'], values='pop', color='lifeExp', hover_data=['iso_alpha'], color_continuous_scale='RdBu', color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop'])) fig.show()
def update_expl_vis_treemap(features, counts, df_input): # print('Draw treemap') clscl = ['rgb(166,206,227)', 'rgb(31,120,180)', 'rgb(178,223,138)', 'rgb(51,160,44)', 'rgb(251,154,153)', 'rgb(227,26,28)', 'rgb(253,191,111)', 'rgb(255,127,0)', 'rgb(202,178,214)', 'rgb(106,61,154)', 'rgb(255,255,153)', 'rgb(177,89,40)'] order = ['Country'] + [feature for feature in features] group_by = ['Country', 'City', 'Group', 'Attack Type', 'Target Type', 'Weapon Type', 'Suicide', 'Success'] agg_on = {'eventid': ['size'], 'Killed': ['sum'], 'Wounded': ['sum']} df_tmp = df_input.groupby(group_by).agg(agg_on).reset_index() df_tmp.columns = ['Country', 'City', 'Group', 'Attack Type', 'Target Type', 'Weapon Type', 'Suicide', 'Success', 'Attack', 'Killed', 'Wounded'] fig = px.treemap(df_tmp, path=order, values=counts, color_discrete_sequence=clscl) fig.update_layout(margin={'l': 40, 'b': 40, 't': 40, 'r': 40}, height=800, hovermode='closest') return fig
def generate_treemap(df): return dcc.Graph(figure=px.treemap(df, path=[df.columns[0]], values=df.columns[1]).update_layout( height=320, margin={ "r": 0, "t": 0, "l": 0, "b": 0 }, paper_bgcolor="#F8F9F9", autosize=True), id='treemap_plot')
def generate_pl_plot(data): data = generate_pl_inputs(data) plotly_fig = px.treemap(data, path=['Investment', 'AllocationType', 'Tickers'], values='Allocation', color='Allocation', color_continuous_scale='Greys') plotly_fig.update_traces(textfont_size=14, hovertemplate='<b>%{label}</b>' + '<br>%{value:.2f}% <br>') plotly_fig.update_layout(coloraxis_showscale=False) plotly_fig.data[0].textinfo = 'label+text+value' graphJSON = json.dumps(plotly_fig, cls=plotly.utils.PlotlyJSONEncoder) return graphJSON
def update_treemap(slider_value, columns): df = combined_data df = df[(df['year'] >= slider_value[0]) & (df['year'] <= slider_value[1])] df = df.sample(frac=0.1, replace=False, random_state=1) df = df.dropna(axis=0) for col in columns: if df[col].dtype == 'float64': df[col] = df[col].astype(int) df['all'] = '' path = ['all'] + columns fig = px.treemap(df, path=path, values='Number_of_Casualties') return fig