def go(): df1 = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/sunburst-coffee-flavors-complete.csv' ) df2 = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/coffee-flavors.csv' ) fig = make_subplots(rows=1, cols=2, column_widths=[0.4, 0.4], specs=[[{ 'type': 'treemap', 'rowspan': 1 }, { 'type': 'treemap' }]]) fig.add_trace(go.Treemap(ids=df1.ids, labels=df1.labels, parents=df1.parents), col=1, row=1) fig.add_trace(go.Treemap(ids=df2.ids, labels=df2.labels, parents=df2.parents, maxdepth=3), col=2, row=1) fig.update_layout(margin={'t': 0, 'l': 0, 'r': 0, 'b': 0}) fig.show()
def covid_26(): global fig3 fig3 = go.Figure() fig3.add_trace( go.Treemap(ids=df["Confirmed"], labels=df["States"], parents=df["Active"], values=df["Active_Value"], textinfo='label+value', domain=dict(column=0))) fig3.add_trace( go.Treemap( ids=df["Confirmed"], labels=df["States"], parents=df["Deaths"], values=df["Deaths_Value"], textinfo='label+value', domain=dict(column=1), )) fig3.update_layout( grid=dict(columns=2, rows=1), margin=dict(t=0, l=0, r=0, b=0), ) fig3.write_html("templates/choro22.html") return render_template("choro22.html")
def test_pie_like_px(): # Pie labels = ["Oxygen", "Hydrogen", "Carbon_Dioxide", "Nitrogen"] values = [4500, 2500, 1053, 500] fig = px.pie(names=labels, values=values) trace = go.Pie(labels=labels, values=values) _compare_figures(trace, fig) labels = [ "Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura" ] parents = ["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve"] values = [10, 14, 12, 10, 2, 6, 6, 4, 4] # Sunburst fig = px.sunburst(names=labels, parents=parents, values=values) trace = go.Sunburst(labels=labels, parents=parents, values=values) _compare_figures(trace, fig) # Treemap fig = px.treemap(names=labels, parents=parents, values=values) trace = go.Treemap(labels=labels, parents=parents, values=values) _compare_figures(trace, fig) # Funnel x = ["A", "B", "C"] y = [3, 2, 1] fig = px.funnel(y=y, x=x) trace = go.Funnel(y=y, x=x) _compare_figures(trace, fig) # Funnelarea fig = px.funnel_area(values=y, names=x) trace = go.Funnelarea(values=y, labels=x) _compare_figures(trace, fig)
def plot_treemap_district(pallete="curl", df=df, template=sport_template): fig = px.treemap(df, path=["All", 'Stadsdeel', "Sport_en"], color="sport_count_in_district", color_continuous_scale=pallete, range_color=[1, 22], hover_name="Sport_en", color_continuous_midpoint=np.average( df["sport_count_in_district"]), maxdepth=3) fig.update_traces( go.Treemap( hovertemplate="%{label}", texttemplate= "%{label}<br><br>Percentage: %{percentParent:.1%} <br>Count: %{value}<br>", outsidetextfont={"size": 20})) fig.update_layout( title=dict( text="Sports Distribution in City Districts<br>(Click to Expand)", ), coloraxis_colorbar=dict(title="Counts", ), margin=dict(l=20, t=100), template=template, ) return fig
def plot_feature_importance(feature_importance): """Created a treemap plot based on feature importance and weights. Args: feature_importance (pandas.DataFrame): A DataFrame describing the feature importances and weights of the trained model. Returns: plotly.graph_objects.Figure: A treemap of the features. """ feature_importance["parent"] = "Feature importance" return go.Figure( go.Treemap( labels=feature_importance.index, parents=feature_importance["parent"], values=feature_importance["gain"], customdata=feature_importance["weight"], marker=dict(colors=feature_importance["weight"], colorscale="greens"), hovertemplate=("<b>%{label}</b><br>importance: %{value:.1%}" "<br>weight: %{customdata:.1%}<extra></extra>"), ), layout={"margin": { "t": 0, "r": 0, "b": 0, "l": 0, }}, )
def plot_treemap_all(pallete="curl", df=df, template=sport_template): fig = px.treemap(df, path=["All", "Sport_en"], color="Sport_count", color_continuous_scale=pallete, range_color=[1, 75], hover_name="Sport_en", color_continuous_midpoint=np.average(df["Sport_count"]), maxdepth=3) fig.update_traces( go.Treemap( textinfo="label", texttemplate= "%{label}<br><br>Percentage: %{percentParent:.1%} <br>Count: %{value}<br>", hovertemplate=" %{label} ", outsidetextfont={"size": 20}, )) fig.update_layout(title=dict( text="Sports Distribution in Amsterdam by Type<br> (Click to Expand)"), coloraxis_colorbar=dict(title="Counts", tickvals=[10, 30, 50, 70]), template=template) return fig
def plot_treemap(self, port): levels = ['ASSET', 'TYPE'] # levels used for the hierarchical chart color_column = 'CHG' aux_color_column = 'CURRENT_TOTAL' value_column = 'TOTAL' df_all_trees = self.__build_hierarchical_dataframe( self.port, levels, value_column, color_column, aux_color_column) trace = go.Treemap( textinfo="label+percent root", labels=df_all_trees['id'], parents=df_all_trees['parent'], values=df_all_trees['value'], branchvalues='total', marker=dict(colors=df_all_trees['color'], colorscale='RdBu', cmid=0), hovertemplate= '<b>%{label} </b> <br> Total: R$%{value:,.2f}<br> Chg: %{color:.2%}', name='') layout = go.Layout(autosize=False, width=1000, height=500, margin=go.layout.Margin(l=10, r=10, b=10, t=10, pad=4)) fig = go.Figure(data=[trace], layout=layout) fig.show()
def plot(nlocs, files, parents, ccns): fig = go.Figure( go.Treemap( labels=files, values=nlocs, parents=parents, marker=dict(colors=ccns, colorscale='blues', cmid=statistics.mean(ccns)), )) fig.show()
def createTreeMap(self,labels=[],parents=[],values=[]): fig = go.Figure(go.Treemap( labels = labels, parents = parents, values = values )) fig.update_layout(margin=dict(l=10, r=10, t=10, b=10),autosize=True) fig.update_yaxes(automargin=True) presult = plotly.offline.plot(fig, config={"displayModeBar": False}, show_link=False, include_plotlyjs=False, output_type='div') return presult
def build_pkd_treemap(voivodeship=[]): df = __df if voivodeship is not None and voivodeship != []: df = df.loc[np.isin(df.MainAddressVoivodeship, voivodeship), :].reset_index(drop=False) pkd_names = __pkd_names levels = ['PKDMainSection', 'PKDMainDivision'] # levels used for the hierarchical chart color_columns = ['DurationOfExistenceInMonths'] value_column = 'Count' df_all_trees = __build_hierarchical_dataframe(df, pkd_names, levels, value_column, color_columns) df_all_trees = __format_strings(df_all_trees) median_duration = df_all_trees['color'].median() max_duration = df_all_trees['color'].max() pkd_fig = go.Figure(go.Treemap( labels=df_all_trees['id'], parents=df_all_trees['parent'], values=df_all_trees['value'], branchvalues='total', marker=dict( colors=df_all_trees['color'], colorscale='balance', cmax=max_duration, cmid=median_duration, colorbar=dict(thickness=20, title='Przetrwane miesiące', titleside='right')), maxdepth=2, # texttemplate = "%{label}<br>%<b>%{customdata[2]}<\b><br>", customdata=df_all_trees[['years', 'months', 'nazwa']], hovertemplate='<b>%{label} </b> <br>%{customdata[2]} <br> - Liczba firm: %{value}<br> - Czas życia przeciętnej firmy: <b>%{customdata[0]}%{customdata[1]}</b>', name='' )) pkd_fig.update_layout( title={ 'text': "Czas życia przeciętnej firmy", 'y': 0.9, 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top' }, margin=dict(l=20, r=20, t=70, b=20), ) return pkd_fig
def draw_treemap(data): fig = go.Figure( go.Treemap( ids=data['id'], parents=data['parent'], labels=data['state'], customdata=data['value'], name='Zones', pathbar={"visible": True}, hovertemplate= '<b> Region: %{label}</b> <br> Zone: %{customdata}<extra></extra>', marker=dict(colors=get_color(data['value'])))) fig.update_layout(title="Zones", height=900, margin=dict(t=30, b=10, r=0, l=0)) return fig
def get_fig(): unique_versions = list(df['version'].unique()) unique_versions.sort() unique_simple_versions = list( [infer_node_version(v) for v in unique_versions]) unique_simple_versions_parents = list( ["All versions" for _ in dict.fromkeys(unique_simple_versions)]) projects_names = list(df['name']) versions = list(df['version']) labels = list(dict.fromkeys(unique_simple_versions)) + \ unique_versions + projects_names parents = unique_simple_versions_parents + unique_simple_versions + versions layout = dict( title=go.layout.Title( text='NodeJS versions in use<br>(Generated on {})'.format( creation_time), font=graph_title_font), paper_bgcolor=WHITE, plot_bgcolor=TRANSPARENT, treemapcolorway=colorway['GovUkColours'], height=600, ) return { 'data': [ go.Treemap( labels=labels, parents=parents, textposition="middle center", tiling=dict(packing="slice", ), marker=dict(line=dict(width=0), ), maxdepth=2, ) ], 'layout': layout }
def milestones_graph(value): tags = list(milestones.keys()) labels = list(milestones.keys()) parents = [''] * len(tags) # fixme: add colors? color = [] counter = 0 stories_color = [] for index, milestone in enumerate(milestones.values()): color = set_milestones_color(milestones, milestone, tags, index, color) for idx, title in enumerate(milestone['title']): if milestone['label'][idx] == 'Bug': stories_color.append('red') elif milestone['label'][idx] == 'Test': stories_color.append('purple') elif milestone['label'][idx] == 'New Feature' or \ milestone['label'][idx] == 'Improvement': stories_color.append('green') else: stories_color.append('gray') parents.append(tags[index]) # When title is present in tags, set new id labels.append(title) if title in tags: # Add issue to treemap but change it's identifier tags.append(title + '_' + str(counter)) counter += 1 else: # Add issue to treemap tags.append(title) # Chain colors for the titles color += stories_color fig = go.Figure(go.Treemap( marker_colors=color, labels=labels, parents=parents, ids=tags )) return fig
def generate_treemap(filtered_df, geo_select): if geo_select is None: hashtag_list = filtered_df['hashtags'].tolist() else: hashtag_list = [point["customdata"] for point in geo_select["points"]] k = 20 hashtags = [hashtag for sublist in hashtag_list for hashtag in sublist] freq_df = pd.DataFrame(list(FreqDist(hashtags).items()),columns=["hashtag","count"]) freq_df = freq_df.sort_values('count',ascending=False) fig = go.Figure(go.Treemap( labels=freq_df['hashtag'][:k].tolist(), values=freq_df['count'][:k].tolist(), parents=['']*k, marker_colorscale=px.colors.sequential.Teal, hovertemplate='<b>%{label} </b> <br>Count: %{value}<extra></extra>')) fig.update_layout(margin=dict(l=0, r=0, t=0, b=10), height=250, plot_bgcolor="#171b26", paper_bgcolor="#171b26") return fig
def treemap_capacity(): levels = ['Country', 'Region', 'Continent'] color_columns = ['capacity_mw', 'quantity'] value_column = 'capacity_mw' df = total_capacity_per_country() df_all_trees = build_hierarchical_dataframe(df, levels, value_column, color_columns) fig = go.Figure() fig.add_trace(go.Treemap(**fig_treemap(df_all_trees))) fig.update_layout( title={ 'text': "Conutries Capacity (MW) Proportional to Numbers of Power Plant <br>(Hoover for more information)", 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top' }, treemapcolorway=[continent_color(c) for c in get_continents()], ) # fig.write_html('tmp3.html', auto_open=True) return plotly.offline.plot(figure_or_data=fig, include_plotlyjs=False, output_type='div')
import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd df2 = pd.read_csv('coffee-flavors.csv') fig = make_subplots(rows=1, cols=2, column_widths=[0.4, 0.4], specs=[[{ 'type': 'treemap', 'rowspan': 1 }, { 'type': 'treemap' }]]) fig.add_trace(go.Treemap(ids=df2.ids, labels=df2.labels, parents=df2.parents, maxdepth=3), col=1, row=1) fig.update_layout(margin={'t': 0, 'l': 0, 'r': 0, 'b': 0}) fig.show()
#%% import plotly.graph_objects as go labels = ["A1", "A2", "A3", "A4", "A5", "B1", "B2"] parents = ["", "A1", "A2", "A3", "A4", "", "B1"] fig = go.Figure( go.Treemap(labels=labels, parents=parents, marker_colors=[ "pink", "royalblue", "lightgray", "purple", "cyan", "lightgray", "lightblue" ])) fig.show()
np_dfBooks[:, 0] == x[4], 1]: parentList.update({x[1]: np_dfBooks[np_dfBooks[:, 0] == x[4], 1]}) else: parentList.update({x[1]: ''}) print(count) print(x[1]) if count == 3827: print(x[1]) print(np_dfBooks[np_dfBooks[:, 0] == x[4], 1]) break count = count + 1 print(parentList.keys()) print(parentList.values()) fig = go.Figure() fig.add_trace( go.Sunburst(labels=list(parentList.keys()), parents=list(parentList.values()), domain=dict(column=0))) fig.update_layout(margin=dict(t=0, l=0, r=0, b=0)) fig.show() #treemap fig1 = go.Figure( go.Treemap( labels=list(parentList.keys()), parents=list(parentList.values()), )) fig1.show()
for cat in categories: modules_onecat = modules_df[modules_df.id.str.startswith(cat)] fig_modules = go.Figure( go.Treemap( branchvalues="remainder", ids=modules_onecat["id"], labels="<b>" + modules_onecat["title"] + "</b> (" + modules_onecat["id"] + ")", parents=modules_onecat["parent"], values=modules_onecat["priority"], marker_colors=modules_onecat["assessment"], text=(modules_onecat["text"]).apply( lambda txt: '<br>'.join(textwrap.wrap(txt, width=100))), textinfo="label+text", hovertext=( modules_onecat["text"] + " (" + modules_onecat["id"] + ")" "<br>Priorität: " + (modules_onecat["priority"]).astype(str) + "<br>Potential: " + (modules_onecat["potential"]).astype(str) ).apply(lambda txt: '<br>'.join(textwrap.wrap(txt, width=100))), hoverinfo="text", pathbar={"visible": True}, insidetextfont={"size": 75})) fig_modules.update_layout(margin=dict(r=10, l=10) # ~ height = 750 ) modules_plot_file.write(
import plotly.graph_objects as go labels = ["A1", "A2", "A3", "A4", "A5", "B1", "B2"] parents = ["", "A1", "A2", "A3", "A4", "", "B1"] marker_colors = [ "pink", "royalblue", "lightgray", "purple", "cyan", "lightgreen", "lightblue" ] fig = go.Figure( go.Treemap(labels=[ "Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura" ], parents=[ "", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve" ], marker_colors=marker_colors)) fig.show()
import plotly.graph_objects as go import pandas as pd #create a dataframe from the Business Capability Model as defined. df = pd.read_csv('data/bcmL1L2L3.csv') print(df) #build a visual treemap of the business capability model via CSV fig = go.Figure(go.Treemap( ids = df.ids, labels = df.labels, parents = df.parents, marker_colorscale = 'Blues')) # marker_colors = ["pink", "royalblue", "lightgray", "purple", "cyan", "lightgray", "lightblue"])) #fig.write_html("bcm.html") fig.update_layout(margin = dict(t=50, l=25, r=25, b=25)) fig.show()
# ~ TOOLTIPS = [ # ~ ("Jahr", "@year"), # ~ ("CO2 (tausend Tonnen)", "@CO2{0.00}"), # ~ ("Prozent von 1990", "@percentage{0.0%}"), # ~ ("Typ", "@type"), # ~ ] # TODO visualise modules fig_modules = go.Figure( go.Treemap( branchvalues="total", labels=[ "Wärme", "Strom", "Verkehr", "W1", "W2", "S1", "S2", "V1", "V2" ], parents=[ "", "", "", "Wärme", "Wärme", "Strom", "Strom", "Verkehr", "Verkehr" ], values=[780, 690, 484, 700, 80, 600, 90, 400, 84], marker_colors=[ "green", "yellow", "red", "green", "green", "red", "green", "red", "red" ], textinfo="label+value+percent parent+percent entry+percent root", )) # ~ fig_modules.write_html('hugo/layouts/shortcodes/modules_' + city + '.html', include_plotlyjs = False, # ~ config={'displayModeBar': False}, full_html = False, auto_open=True)
text=top_labels[i], font=dict(family='Arial', size=14, color='rgb(67, 67, 67)'), showarrow=False)) space += xd[i] fig.update_layout( title="Age ratio distribution by gender", annotations=annotations) fig.show() y = dist.Country.value_counts() fig = go.Figure(go.Treemap( labels = y.index, parents = ['World'] * len(y), values = y )) fig.update_layout(title = '# of Survey Participants') fig.show() dist_ratio = dist.groupby('Country')['Gender'].value_counts().unstack().fillna(0) dist_ratio['Female/Male'] = dist_ratio['Female'] / dist_ratio['Male'] print('Average female / male ratio') print(sum(dist_ratio['Female']) / sum(dist_ratio['Male'])) dist_ratio['Country'] = dist_ratio.index fig = px.choropleth(dist_ratio, locations='Country', locationmode='country names', color="Female/Male", color_continuous_scale=[[0.0, "rgb(165,0,38)"],
for i in fields: info['Summary'] = info['Summary'] + i + ': ' + info[i].astype(str) + '<br><br>' args = dict(data_frame=info, values='Number of studies', color='Number of studies', hover_data='', path=['Focus', 'Tissue condition', 'Human/animal', 'Condition', 'Study'], color_continuous_scale='Viridis') args = px._core.build_dataframe(args, go.Treemap) treemap_df = px._core.process_dataframe_hierarchy(args)['data_frame'] fig2 = go.Figure(go.Treemap( ids=treemap_df['id'].tolist(), labels=treemap_df['labels'].tolist(), parents=treemap_df['parent'].tolist(), values=treemap_df['Number of studies'].tolist(), branchvalues='total', text=info['Summary'], hoverinfo='label', textfont=dict( size=15, ) ) ) fig2 = fig2.update_layout( autosize=False, width=680, height=600, margin=dict( l=0, r=0, t=0,
] df = pd.DataFrame( dict(States=States, Confirmed=Confirm, Deaths_Value=Deaths_value)) df["States_in_US"] = "States_in_US" df["Deaths"] = "Deaths" df["Active_Value"] = df["Active"] = df["Confirmed"] - df["Deaths_Value"] df["Active"] = "Active" df.head(60) fig3 = go.Figure() fig3.add_trace( go.Treemap(ids=df["Confirmed"], labels=df["States"], parents=df["Active"], values=df["Active_Value"], textinfo='label+value', domain=dict(column=0))) fig3.add_trace( go.Treemap( ids=df["Confirmed"], labels=df["States"], parents=df["Deaths"], values=df["Deaths_Value"], textinfo='label+value', domain=dict(column=1), )) fig3.update_layout( grid=dict(columns=2, rows=1),
rgbPallete = [] for counter in range(len(pallete)): r = pallete[counter][0] g = pallete[counter][1] b = pallete[counter][2] color = "rgb({},{},{})".format(r, g, b) rgbPallete.append(color) fig = go.Figure() fig.add_trace( go.Treemap( labels=df_all_trees['id'], parents=df_all_trees['parent'], values=df_all_trees['value'], branchvalues='total', name="", marker=dict(colors=df_all_trees['color'], colorscale=rgbPallete, cmid=average_score), hovertemplate= '<b>%{label} </b> <br> Número de drones: %{value}<br> Porcentagem do total: %{color:.2f}', maxdepth=2)) fig.update_layout(margin=dict(t=15, b=15, r=15, l=15), autosize=True) plotly.io.write_html( fig, file="./../website/webviews/treemap-proprietarios.html", full_html=False, default_height="80%")
color='R^2', hover_data='', path=['Measure', 'Study'], color_continuous_scale='Viridis') args = px._core.build_dataframe(args, go.Treemap) treemap_df = px._core.process_dataframe_hierarchy(args)['data_frame'] fig4 = go.Figure( go.Treemap(ids=treemap_df['id'].tolist(), labels=treemap_df['labels'].tolist(), parents=treemap_df['parent'].tolist(), values=treemap_df['Sample points'].tolist(), branchvalues='total', text='R<sup>2</sup>: ' + filtered_df['R^2'].astype(str) + '<br>' + filtered_df['Details'], hovertext=filtered_df['Study'] + '<br>R<sup>2</sup>: ' + filtered_df['R^2'].astype(str) + '<br>Number of samples: ' + filtered_df['Sample points'].astype(str), hoverinfo='text', textfont=dict(size=15, ), marker=dict(colors=filtered_df['R^2'], colorscale='Viridis', colorbar=dict(title='R<sup>2</sup>'), showscale=True))) fig4 = fig4.update_layout( title=dict(text="Figure 4 - R<sup>2</sup> values across studies"), autosize=False, width=650, height=600, margin=dict(l=0))
def get(token: str, file_id: int): def log(*args): print(f'[{token[:4]}]', *args) client = putiopy.Client(token) files: Dict[int, File] = {} processed = 0 try: root = client.File.get(file_id) except putiopy.ClientError as e: if e.response.status_code == 401 and file_id == 0: raise ExpiredToken raise total_size = root.size log("total size of file(%d): %d gb" % (file_id, total_size // 2**30)) def append_children_recursive(putio_file, total_sizes: Queue, level: int) -> None: nonlocal processed children = list_children(putio_file.id, client) threads = [] children_sizes: Queue[int] = Queue() for child in children: if child.folder_type == 'SHARED_ROOT': continue if (level < MAX_LEVEL and child.content_type == 'application/x-directory'): t = threading.Thread(target=append_children_recursive, args=(child, children_sizes, level + 1)) t.start() threads.append(t) else: children_sizes.put(child.size) files[child.id] = File(child, child.size) processed += child.size log("processed %d of %d gb" % (processed // 2**30, total_size // 2**30)) for t in threads: t.join() children_size = 0 while True: try: children_size += children_sizes.get_nowait() except Empty: break dir_size = putio_file.size if children_size > dir_size: dir_size = children_size total_sizes.put(dir_size) files[putio_file.id] = File(putio_file, dir_size) start = time.time() append_children_recursive(root, Queue(), level=1) end = time.time() log('file tree traversed in %s seconds' % (end - start)) ids = [] labels = [] values = [] parents = [] for id, file in files.items(): ids.append(file.id) labels.append(file.name) values.append(file.size) try: parents.append(files[file.parent_id].id) except KeyError: parents.append('') fig = go.Figure( go.Treemap( ids=ids, labels=labels, values=values, parents=parents, branchvalues='total', texttemplate='%{label}', hovertemplate='%{label}<br>%{value:.2s}<extra></extra>', )) return fig.to_html(include_plotlyjs='cdn')
def visualize_plotly(acts, title=None, treemap=True, sunburst=True): # @warn this is not async, and it takes rather long to complete ## out_links = [] out_files = [] if timedelta_total_seconds(acts.total_duration) == 0: return out_links, out_files all_acts = get_acts(acts) acts_agg = all_acts[0] # print(acts_agg) ids = [act.name for act in all_acts] labels = [ f"{act.shortname} {(timedelta_total_seconds(act.total_duration)*100/timedelta_total_seconds(acts_agg.total_duration)):.1f}%" for act in all_acts ] texts = [timedelta_str(act.total_duration) for act in all_acts] ## parents = [(act.parent and act.parent.name) or "" for act in all_acts] values = [(timedelta_total_seconds(act.total_duration) / (3600)) for act in all_acts] # Do NOT round the values. Plotly expects them to sum correctly or something. ## Test out input values: # lim=19 # labels = labels[:lim] # parents = parents[:lim] # values = values[:lim] # print(labels) # print(texts) # print(parents) # print(values) ## # https://plotly.com/python/treemaps/ # https://plotly.com/python/reference/treemap/ plot_opts = dict( branchvalues="total", ids=ids, labels=labels, parents=parents, values=values, text=texts, # %{value:.1f} texttemplate= "%{label}<br>%{text}<br>%{percentParent:.1%} of %{parent}<br>%{percentEntry:.1%} of %{entry}<br>%{percentRoot:.1%} of %{root}", # textinfo = "label+value+percent parent+percent entry+percent root", # %{currentPath}%{label} hovertemplate= "%{label}<br>%{text}<br>%{percentParent:.1%} of %{parent}<br>%{percentEntry:.1%} of %{entry}<br>%{percentRoot:.1%} of %{root}<extra>%{id}</extra>", # https://community.plotly.com/t/how-to-explicitly-set-colors-for-some-sectors-in-a-treemap/51162 # color="day", # color_discrete_map={'(?)':'gold', 'Study':'green', 'wasted':'black'}, ) ## colors @unresolved https://community.plotly.com/t/how-to-explicitly-set-colors-for-some-sectors-in-a-treemap/51162 def choose_color(i, act, parent_names=None, cmap=cmaps["alphabet"]): if parent_names == None: parent_names = act.name.split("_") longname = "_".join(parent_names) if longname in categories: return categories[longname] parent_names = parent_names[:-1] if len(parent_names) >= 1: return choose_color(i, act, parent_names) else: return cmap[abs( (hash(longname) % len(cmap)) )] # abs is redundant: Python modulo operator always return the remainder having the same sign as the divisor. cs = [choose_color(i, act) for i, act in enumerate(all_acts)] if treemap: fig = go.Figure(go.Treemap(**plot_opts)) # fig.update_layout(margin = dict(t=0, l=0, r=0, b=0)) fig.update_layout(margin=dict(t=30, l=0, r=30, b=30)) # fig.update_layout(uniformtext=dict(minsize=6, mode='hide')) fig.update_traces(marker_colors=cs) fig.update_traces(marker_depthfade=True) if title: fig.update_layout(title_text=title) fig.update_layout(title_font_size=11) # fig.update_layout(title_x=0.1) is_local and fig.show() l, f = fig_export(fig, "treemap", width=400, height=400, svg_export=False, pdf_export=False) out_links += l # is list out_files += f ## if sunburst: # @unresolved https://community.plotly.com/t/show-the-current-path-bar-in-sunburst-plots-just-like-treemap-plots/51155 plot_opts["labels"] = [act.shortname for act in all_acts] plot_opts["texttemplate"] = "%{label}<br>%{text}, %{percentRoot:%}" fig = go.Figure(go.Sunburst(**plot_opts)) fig.update_layout(margin=dict(t=0, l=0, r=0, b=0)) # fig.update_layout(uniformtext=dict(minsize=6, mode='hide')) fig.update_traces(marker_colors=cs) if title: fig.update_layout(title_text=title) fig.update_layout(title_font_size=11) fig.update_layout(title_y=0.99) is_local and fig.show() l, f = fig_export(fig, "sunburst", width=400, height=400, svg_export=False, pdf_export=False) out_links += l # is list out_files += f return out_links, out_files
import plotly.graph_objects as go import plotly.offline as py #values = ["12", "12", "13", "14", "15", "20", "30"]parents = ["", "Lung cancer", "Colorectal cancer", "Non-melanoma skin cancer", "prostate cancer ", "breast cancer", "", "the leading cause of cancer deaths", "Second most common cause of Cancer deaths"] import plotly.graph_objects as go import plotly.io as pio labels = ["Lung cancer", "Colorectal cancer", "Non-melanoma skin cancer", "Prostate cancer", "Breast cancer"] parents = ["", "Lung cancer", "Colorectal cancer", "Non-melanoma skin cancer", "Prostate cancer", "Breast cancer"] values = ["2749", "1900", "10000", "3665", "3100"] fig = go.Figure(go.Treemap( labels = labels, parents = parents, values = values, marker_colors = ["beige", "royalblue", "black", "lightblue", "pink", "lightgray", "pink"] )) fig.show() py.iplot(fig) py.plot(fig, filename='tre.html') pio.write_html(fig, file= 'index.html', auto_open=True)