def plot_sunbirst_charts(solved_data: pd.DataFrame): sb1 = px.sunburst(solved_data, values="expense", path=["type", "entity"])._data sb2 = px.sunburst( solved_data[solved_data["solution"] == 1], values="expense", path=["type", "entity"], )._data # use data and structure FROM sb1 and sb2 (trick) fig = make_subplots(rows=1, cols=2, specs=[[{ "type": "domain" }, { "type": "domain" }]]) fig.add_trace( go.Sunburst( branchvalues="total", labels=sb1[0]["labels"], parents=sb1[0]["parents"], values=sb1[0]["values"], ), 1, 1, ) fig.add_trace( go.Sunburst( branchvalues="total", labels=sb2[0]["labels"], parents=sb2[0]["parents"], values=sb2[0]["values"], ), 1, 2, ) fig.update_layout( title_text="Expenses distribution in solution, sunbirst chart", # Add annotations in the center of the donut pies. annotations=[ dict(text="Original", x=0.17, y=1.1, font_size=20, showarrow=False), dict(text="Optimized", x=0.84, y=1.1, font_size=20, showarrow=False), ], ) # fig = go.Figure(data = [trace1, trace2], layout = layout) fig.show()
def make_plot(white_moves, black_moves): fig = make_subplots(rows=1, cols=2, specs=[[{'type': 'domain'}, {'type': 'domain'}]], subplot_titles=('White', 'Black')) fig.add_trace(go.Sunburst( name='M is white', ids=white_moves['ids'], labels=white_moves['labels'], parents=white_moves['parents'], values=white_moves['values'], branchvalues="total", opacity=1, marker={'colors': white_moves['color'], 'line': {'color': '#000200'}}, hoverinfo='label+text+name+current path+value', hovertext='Win: ' + white_moves['win'].apply(str) + '\nDraw: ' + white_moves['draw'].apply(str) + '\nLose: ' + white_moves['lose'].apply(str) ), row=1, col=1) fig.add_trace(go.Sunburst( name='M is black', ids=black_moves['ids'], labels=black_moves['labels'], parents=black_moves['parents'], values=black_moves['values'], branchvalues="total", opacity=1, marker={'colors': black_moves['color'], 'line': {'color': '#000200'}}, hoverinfo='label+text+name+current path+value', hovertext='Win: ' + black_moves['win'].apply(str) + '\nDraw: ' + black_moves['draw'].apply(str) + '\nLose: ' + black_moves['lose'].apply(str) ), row=1, col=2) fig.update_layout( height=750, width=1500, margin={'t': 0, 'l': 2, 'r': 2, 'b': 0}, paper_bgcolor='#000200', plot_bgcolor='#000200', uniformtext={'minsize': 11, 'mode': 'hide'}, title={'text': 'First five moves of Magnus Carlsen games since he became the world champion', 'font': {'size': 18, 'color': '#ffffff'}, 'y': 0.98, 'x': 0.5} ) return fig
def build_sunburst(): story_id = "" fig = go.Figure( go.Sunburst( ids=df.id, labels=df.name, parents=df.parent, values=df.page_duration, branchvalues="total", customdata=customdata_df, # domain=dict(column=0), sort=False, level=story_id, rotation=90, maxdepth=5, insidetextfont=dict(size=10), insidetextorientation="radial", marker=dict(colors=df["color"]), leaf=dict(opacity=1), hovertemplate="<extra></extra><b>%{label} </b> <br> Night Duration: %{customdata[0]}</b> <br> Page Duration:%{value} </b> <br> Gender Mention Ratio (Female/Male):%{customdata[2]: .2f}<br>", ) ) fig.update_layout(margin=dict(t=0, l=0, r=0, b=0)) fig.update_layout(paper_bgcolor=bg_color) return fig
def make_sunburst(df, path, values, title): if len(path) > 2: hover = "<b>%{label} </b><br> %{percentRoot:,.1%} </br> %{value:$,.0f} </br>" else: hover = "<b>%{label} </b><br> %{percentRoot:,.1%} </br> " fig = px.sunburst( df, path=path, values=values, hover_data=["Per Capita_2017"], color="Category", color_discrete_map=du.sunburst_colors, ) fig.update_traces( go.Sunburst(hovertemplate=hover), insidetextorientation="radial", ) fig.update_layout( title_text=title, title_x=0.5, title_xanchor="center", title_yanchor="top", margin=go.layout.Margin(b=10, t=30, l=10, r=10), clickmode="event+select", ) return fig
def create_sunburst_fig_title(caller): """Create the sunburst by sunburst_dict.""" if caller == 'ba': sunburst_info, sunburst_title = hold_up_ba elif caller == 'ma': sunburst_info, sunburst_title = hold_up_ma fig = go.Figure( go.Sunburst(parents=sunburst_info['parent'], labels=sunburst_info['character'], values=sunburst_info['value'], branchvalues="total", marker=dict( colors=sunburst_info['value'], colorscale='Cividis', ))) fig.update_layout( # autosize=False, margin={ "t": 0, "l": 0, "r": 0, "b": 0, "pad": 0, }, showlegend=True, height=512, ) return fig, sunburst_title
def make_sunburst(df, path, values, title): fig = px.sunburst(df, path=path, values=values, color="Category", color_discrete_map=du.sunburst_colors # hover_data=['Population'] ) fig.update_traces( go.Sunburst( # hovertemplate='<b>%{label} </b> <br>%{customdata[0]}<br> $%{value:,.0f}' hovertemplate="<b>%{label} </b> $%{value:,.0f}"), insidetextorientation="radial", ) fig.update_layout( title_text=title, title_x=0.5, title_xanchor="center", title_yanchor="top", # title_y=0.95, margin=go.layout.Margin(b=10, t=10, l=1, r=1), # yaxis=go.layout.YAxis(tickprefix="$", fixedrange=True), # xaxis=go.layout.XAxis(fixedrange=True), # annotations=total_labels, # paper_bgcolor="whitesmoke", clickmode="event+select", ) return fig
def graph(): fig = go.Figure( go.Sunburst(labels=[ "Población Vulnerable", "3era Edad", "Discapacidad o Limitación", "Condición Mental", "Visual o Auditiva", "Hablar o Comunicarse", "Motriz", "Recordar o concentrarse", "Condición mental", "Ver, aún usando lentes", "Oir, aún usando aparatos", "Caminar, subir o bajar", "Bañarse, vestirse o comer" ], parents=[ "", "Población Vulnerable", "Población Vulnerable", "Población Vulnerable", "Población Vulnerable", "Población Vulnerable", "Población Vulnerable", "Condición Mental", "Condición Mental", "Visual o Auditiva", "Visual o Auditiva", "Motriz", "Motriz" ], values=[ 46200, 17600, 12568, 2466, 8140, 485, 4941, 982, 1484, 6311, 1829, 4147, 794 ], branchvalues="total", textinfo='label+percent entry')) fig.update_layout(margin=dict(t=0, l=0, r=0, b=0), height=600) return dcc.Graph(figure=fig)
def get_http_code_fig(): l, sum_2, sum_3, sum_4, sum_5, SUM = obj.get_http_status_data() # print(l, sum_2, sum_3, sum_4, sum_5, SUM) SUM += 15000 sum_3 += 700 l[2] += 237 l[3] += 243 l[4] += 20 fig = go.Figure( go.Sunburst( labels=[ "HTTP Status Code", "2xx", "3xx", "4xx", "5xx", "200", "202", "301", "302", "307", "400", "401", "403", "404", '408', '500', '502', '503' ], parents=[ "", "HTTP Status Code", "HTTP Status Code", "HTTP Status Code", "HTTP Status Code", "2xx", "2xx", "3xx", "3xx", "3xx", '4xx', '4xx', '4xx', '4xx', '4xx', '5xx', '5xx', '5xx' ], values=[SUM, sum_2, sum_3, sum_4, sum_5] + l, branchvalues="total", marker=dict(colorscale='Blackbody', ), # Rainbow Jet Blackbody hovertemplate='<b>%{label} </b> <br> Count: %{value}', name='', # 不显示trace0\trace1... # maxdepth=2 )) fig.update_layout(margin=dict(t=0, l=0, r=0, b=0)) return fig
def get_domain_host_type_fig(): labels = [ 'Host Type', '企业', '事业单位', '政府机关', '社会团体', '民营非企业单位', '民办非企业单位', '个人', '群众性团体组织', '律师执业机构', '群团组织', '基金会' ] + ['门户网站', '后台系统'] * 11 parents = [''] + ['Host Type'] * 11 + [ '企业', '企业', '事业单位', '事业单位', '政府机关', '政府机关', '社会团体', '社会团体', '民营非企业单位', '民营非企业单位', '民办非企业单位', '民办非企业单位', '个人', '个人', '群众性团体组织', '群众性团体组织', '律师执业机构', '律师执业机构', '群团组织', '群团组织', '基金会', '基金会' ] res = obj.get_domain_host_type_fig_values([ '企业', '事业单位', '政府机关', '社会团体', '民营非企业单位', '民办非企业单位', '个人', '群众性团体组织', '律师执业机构', '群团组织', '基金会' ]) values = [22875, 10630, 7578, 3504, 563, 275, 175, 110, 22, 12, 5, 1] + res # print(len(labels), len(parents), len(values)) # print(labels) # print(parents) # print(values) fig = go.Figure( go.Sunburst( labels=labels, parents=parents, values=values, branchvalues="total", hovertemplate='<b>%{label} </b> <br> Count: %{value}', name='', # 不显示trace0\trace1... )) fig.update_layout(margin=dict(t=0, l=0, r=0, b=0)) return fig
def get_prod_share_trace(episode): prod_types = episode.get_prod_types() prod_type_values = list(prod_types.values()) if len( prod_types.values()) > 0 else [] share_prod = observation_model.get_prod(episode) df = share_prod.groupby("equipment_name")["value"].sum() unique_prod_types = np.unique(prod_type_values) labels = [*df.index.values, *np.unique(prod_type_values)] parents = [prod_types.get(name) for name in df.index.values] #labelTypes=[l if l in dic_colors_prod_types.keys() else prod_types.get(l) for l in labels] colors=[dic_colors_prod_types[l] if l in dic_colors_prod_types.keys() else dic_light_colors_prod_types[prod_types.get(l)] for l in labels] values = list(df) for prod_type in unique_prod_types: parents.append("") value = 0 for gen in df.index.values: if prod_types.get(gen) == prod_type: value = value + df.get(gen) values.append(value) return [go.Sunburst(labels=labels, values=values, parents=parents, branchvalues="total", marker = dict(colors=colors, colorscale='RdBu'))]
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 sunburst_plot(_stats: Dict, show=True, save=True): data_comp = go.Figure( go.Sunburst( labels=LABELS, parents=[ 'RSNA_ICH', 'RSNA_ICH', 'training', 'training', 'any', 'any', 'any', 'any', 'any', ], values=[_stats[_l].cnt for _l in LABELS], branchvalues='remainder', )) print([_stats[_l].cnt for _l in LABELS]) data_comp.update_layout(margin=dict(t=0, l=0, r=0, b=0), height=1080, width=1440) if show: data_comp.show() if save: data_comp.write_image( os.path.join(ICH_DIR, 'data_composition_sunburst.png'))
def get_prod_share_trace(episode): prod_types = episode.get_prod_types() prod_type_values = list( prod_types.values()) if len(prod_types.values()) > 0 else [] share_prod = observation_model.get_prod(episode) df = share_prod.groupby("equipment_name")["value"].sum() unique_prod_types = np.unique(prod_type_values) labels = [*df.index.values, *np.unique(prod_type_values)] parents = [prod_types.get(name) for name in df.index.values] values = list(df) for prod_type in unique_prod_types: parents.append("") value = 0 for gen in df.index.values: if prod_types.get(gen) == prod_type: value = value + df.get(gen) values.append(value) return [ go.Sunburst(labels=labels, values=values, parents=parents, branchvalues="total") ]
def bloch_sunburst(vec, colormap): """Create a Bloch disc using a Plotly sunburst. Parameters: vec (ndarray): A vector of Bloch components. colormap (Colormap): A matplotlib colormap. Returns: go.Figure: A Plotly figure instance, Raises: ValueError: Input vector is not normalized. """ eps = 1e-6 vec = np.asarray(vec) vec_norm = np.linalg.norm(vec) if vec_norm > 1.0 + eps: raise ValueError( 'Input vector has length {} greater than 1.0'.format(vec_norm)) for idx, val in enumerate(vec): if abs(val) < 1e-15: vec[idx] = 0 th = math.atan2(vec[1], vec[0]) if th < 0: th = 2 * np.pi + th z_hex = matplotlib.colors.rgb2hex(colormap(NORM(vec[2]))) z_color = "rgba({},{},{},{})".format(*hex_to_rgb(z_hex), 0.95 * vec_norm + 0.05) ring_color = "rgba({},{},{},{})".format(*hex_to_rgb('#000000'), 0.95 * vec_norm + 0.05) wedge_str = "\u2329X\u232A= {x}<br>" wedge_str += "\u2329Y\u232A= {y}<br>" wedge_str += "\u2329Z\u232A= {z}<br>" wedge_str += " \u03B8 = {th}<br>" wedge_str += "|\u03C8| = {pur}" th_str = pi_check(th, ndigits=3) th_str = th_str.replace('pi', '\u03C0') hover_text = [ wedge_str.format(x=round(vec[0], 3), y=round(vec[1], 3), z=round(vec[2], 3), th=th_str, pur=np.round(vec_norm, 3)) ] + [None] bloch = go.Sunburst(labels=[" ", " "], parents=["", " "], values=[2 * np.pi - th, th], hoverinfo="text", hovertext=hover_text, marker=dict(colors=[z_color, ring_color])) return bloch
def fig(self): fig = go.Figure( go.Sunburst(ids=self.ids, labels=self.labels, parents=self.parents, values=self.values)) return fig
def generate_sunburst(directories: Dict[Path, Tuple[int, int]], root: Path) -> go.Sunburst: """Generate a sunburst chart from the directories given in input.""" max_depth = compute_max_depth(list(directories.keys())) metrics_columns = ["contents", "known"] levels_columns = ["lev" + str(i) for i in range(max_depth)] df_columns = levels_columns + metrics_columns dirs_df = generate_df_from_dirs(directories, df_columns, max_depth) hierarchical_df = build_hierarchical_df(dirs_df, levels_columns, metrics_columns, str(root)) sunburst = go.Sunburst( labels=hierarchical_df["id"], parents=hierarchical_df["parent"], values=hierarchical_df["contents"], branchvalues="total", marker=dict( colors=hierarchical_df["known"], colorscale="matter", cmid=50, showscale=True, ), hovertemplate="""<b>%{label}</b> <br>Files: %{value} <br>Known: <b>%{color:.2f}%</b>""", name="", ) return sunburst
def plotly(): x = list(range(10)) fig = go.Figure(data=go.Scatter(x=x, y=[i**2 for i in x])) html1 = fig.to_html(include_plotlyjs="require", full_html=False) fig = go.Figure(data=[ go.Scatter(x=[1, 2, 3, 4], y=[10, 11, 12, 13], mode='markers', marker=dict( color=[ 'rgb(93, 164, 214)', 'rgb(255, 144, 14)', 'rgb(44, 160, 101)', 'rgb(255, 65, 54)' ], opacity=[1, 0.8, 0.6, 0.4], size=[40, 60, 80, 100], )) ]) html2 = fig.to_html(include_plotlyjs="require", full_html=False) fig = go.Figure( go.Sankey( arrangement="snap", node={ "label": ["A", "B", "C", "D", "E", "F"], "x": [0.2, 0.1, 0.5, 0.7, 0.3, 0.5], "y": [0.7, 0.5, 0.2, 0.4, 0.2, 0.3], 'pad': 10 }, # 10 Pixels link={ "source": [0, 0, 1, 2, 5, 4, 3, 5], "target": [5, 3, 4, 3, 0, 2, 2, 3], "value": [1, 2, 1, 1, 1, 1, 1, 2] })) html3 = fig.to_html(include_plotlyjs="require", full_html=False) fig = go.Figure( go.Sunburst( 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], )) # Update layout for tight margin # See https://plotly.com/python/creating-and-updating-figures/ fig.update_layout(margin=dict(t=0, l=0, r=0, b=0)) html4 = fig.to_html(include_plotlyjs="require", full_html=False) put_grid([[put_html(html1), put_html(html2)], [put_html(html3), put_html(html4)]], cell_width='1fr', cell_height='1fr')
def create_sunburst_fig(sunburst_info: dict): # --> fig: """Create the sunburst by sunburst_dict.""" fig = go.Figure( go.Sunburst(parents=sunburst_info['parent'], labels=sunburst_info['character'], values=sunburst_info['value'], branchvalues="total", marker=dict( colors=sunburst_info['value'], colorscale='Cividis', ))) fig.update_layout( # autosize=False, margin={ "t": 0, "l": 0, "r": 0, "b": 0, "pad": 0, }, showlegend=True, height=512, ) # print(sunburst_info) return fig
def plot1(path): data = pd.read_csv(path / 'raw_data.csv', index_col=0) fig = make_subplots(rows=1, cols=2, specs=[[{ 'type': 'domain' }, { 'type': 'domain' }]]) values = data['Gender'].value_counts(dropna=False).values.tolist() labels = data['Gender'].value_counts(dropna=False).index.tolist() labels = ['Missing', 'Male', 'Female'] fig.add_trace( go.Pie(labels=labels, values=values, textinfo='label+percent', insidetextorientation='radial'), 1, 1) fig.update_traces(hole=0.35) fig.update_layout(annotations=[ dict(text='Gender', x=0.15, y=0.5, font_size=18, showarrow=False) ]) data['Transmission_Type'] = data['Transmission_Type'].apply( lambda x: 'Unknown' if str(x) == 'nan' else str(x).strip()) values = data['Transmission_Type'].value_counts().values.tolist() labels = data['Transmission_Type'].value_counts().index.tolist() for label, value in zip(labels, values): if ((label == 'TBD') | (label == 'Unknown')): values.append(value) labels.append('Unknown') labels[labels.index('Unknown')] = 'Missing' values[-2] = values[-2] + values[-1] values = values[:-1] values.insert(0, sum(values[:-1])) labels.insert(0, 'Transmission') parents = [ '', 'Unknown', 'Transmission', 'Unknown', 'Transmission', 'Transmission' ] fig.add_trace( go.Sunburst(labels=labels, parents=parents, values=values, branchvalues='total', textinfo='label+percent root', insidetextorientation='radial'), 1, 2) fig.update_traces(hoverinfo='value', textfont_size=15) fig.update_layout(font=dict(family="Courier New, monospace"), showlegend=False, margin=dict(l=20, r=20, t=50, b=50)) return fig
def plot_sources_hierarchical(source_info_1, source_info_2): """ Create a sunburst chart combining different kinds of information about the sources, e.g. the kinds of editions and the type of institution or the filetypes and the sources. Arguments: source_info_1 (str): which kind of source information to plot as the inner circle / parents. Possible values: "sources_medium", "sources_filetype", "sources_institution", "sources_edition", "institution_type" source_info_2 (str): which kind of source information to plot as the outer circle / parents. Possible values are the same as for source_info_1. """ data_dir = "/home/ulrike/Git/data-nh/corpus/corpus-sources/" data = pd.read_csv(join(data_dir, "../metadata_sources.csv"), index_col=0) data_grouped_level_1 = data.groupby([source_info_1, source_info_2]).size() data_grouped_level_0 = data_grouped_level_1.sum(level=0) labels_level_0_set = list(data_grouped_level_1.keys().levels[0]) labels_level_0_all = list(data_grouped_level_1.index.get_level_values(0)) labels_level_1 = list(data_grouped_level_1.index.get_level_values(1)) labels = labels_level_0_set + labels_level_1 values = list(data_grouped_level_0) + list(data_grouped_level_1) ids = labels_level_0_set + [ str(i[0]) + "-" + str(i[1]) for i in zip(labels_level_0_all, labels_level_1) ] parents = ["" for i in range(len(labels_level_0_set))] + labels_level_0_all colors = [ "rgb(31, 119, 180)", "rgb(255, 127, 14)", "rgb(44, 160, 44)", "rgb(214, 39, 40)" ] #"rgb(44, 160, 44)", "rgb(214, 39, 40)" fig = go.Figure( go.Sunburst(ids=ids, labels=labels, parents=parents, values=values, marker=dict(colors=colors), branchvalues="total", textinfo="label+percent entry", textfont=dict(size=16))) fig.update_layout(autosize=False, width=800, height=800) outfile = source_info_1 + "_" + source_info_2 fig.write_image(join(data_dir, outfile + ".png")) # scale=2 (increase physical resolution) fig.write_html( join(data_dir, outfile + ".html" )) # include_plotlyjs="cdn" (don't include whole plotly library) #fig.show() print("done")
def victims_sunburst_update(input_race, input_region, input_sex, input_state): df_local = filter_data(df_victims_sunburst, input_race=input_race, input_region=input_region, input_sex=input_sex, input_state=input_state ) df_local = build_hierarchical_dataframe(df_local, ['Race4', 'Race3', 'Race2'], 'Victim') fig = go.Figure() # https://plotly.com/python/reference/sunburst/#sunburst-text fig.add_trace(go.Sunburst( labels=df_local["id"], parents=df_local["parent"], values=df_local["value"], branchvalues="total", text=df_local[['percentage']], textinfo='label', maxdepth=4, marker=dict( colors=df_local['color'], colorscale='RdBu', cmid=0.5, line=dict( width=1 ) ), insidetextfont=dict( size=16, family="Rockwell" ), insidetextorientation='tangential', hovertemplate='<b>%{label} </b> <br> <i>Victims: </i>%{value}<br>'+ '<i>Percentage: </i>%{text[0]} % <br>' + '<extra></extra>', )) fig.update_layout( plot_bgcolor="white", hoverlabel=dict( bgcolor="white", font_size=16, font_family="Rockwell" ), hoverlabel_align = 'right', margin = dict(t=0, l=0, r=0, b=0), height = 550, width = 550 ) return fig
def sunburst_fig(): df = pd.read_csv( 'https://github.com/nchelaru/data-prep/raw/master/telco_cleaned_renamed.csv' ) ## Get categorical column names cat_list = [] for col in df.columns: if df[col].dtype == object: cat_list.append(col) ## Get all possible levels of every categorical variable and number of data points in each level cat_levels = {} for col in cat_list: levels = df[col].value_counts().to_dict() cat_levels[col] = levels ## Convert nested dictionary to dataframe nestdict = pd.DataFrame(cat_levels).stack().reset_index() nestdict.columns = ['Level', 'Category', 'Population'] nestdict['Category'] = [s + ": " for s in nestdict['Category']] cat_list = nestdict['Category'].unique() empty_list = [None] * len(cat_list) pop_list = ['0'] * len(cat_list) df1 = pd.DataFrame() df1['Level'] = cat_list df1['Category'] = empty_list df1['Population'] = pop_list df = pd.concat([df1, nestdict]) df['Population'] = df['Population'].astype(int) fig = go.Figure( go.Sunburst(labels=df['Level'], parents=df['Category'], values=df['Population'], leaf={"opacity": 0.4}, hoverinfo='skip')) fig.update_layout(width=700, height=900, margin=dict(t=0, l=0, r=0, b=0)) return fig
def form(ids, labels, parents, values): fig = go.Figure( go.Sunburst( ids=ids, labels=labels, parents=parents, values=values, branchvalues= 'total', # if children exceed parent, graph will crash and not show insidetextorientation='horizontal' # text displays PP )) return fig
def plot_sunburst_static( df, value_column, levels=["land", "region_wb"], color_columns=None, _colors=colors.sequential.PuBu, value_column_name="", ): color = "#1f2630" df_sunburst = build_hierarchical_dataframe(df, levels, value_column, color_columns) if color_columns is not None: hovertemplate = ("<b>%{label} </b> <br> " + value_column_name + ": %{value}<br> per 100k: %{color:.0f}") average_score = df_sunburst["color"].median() min_score = df_sunburst["color"].quantile(0.1) max_score = df_sunburst["color"].quantile(0.9) fraction_series = df_sunburst["color"] else: hovertemplate = "<b>%{label} </b> <br> " + value_column_name + ": %{value}<br>" average_score = df[value_column].median() min_score = df[value_column].quantile(0.1) max_score = df[value_column].quantile(0.9) fraction_series = df[value_column] fig = go.Figure() fig.add_trace( go.Sunburst( labels=df_sunburst["id"], parents=df_sunburst["parent"], values=df_sunburst["value"], branchvalues="total", marker=dict( colors=fraction_series, colorscale=_colors, # reversescale=True, cmid=average_score, cmax=max_score, cmin=min_score, ), hovertemplate=hovertemplate, name="", )) fig.update_layout( margin=dict(t=10, b=10, r=10, l=10), plot_bgcolor=color, paper_bgcolor=color, ) return fig
def update_graph_live(n): # input source for data - BEGIN f = open('edgebox1.txt', 'r') # num_edgebox1 = f.read() col_edgebox1 = define_color(f.read()) f.close() f = open('edgebox1_vm1.txt', 'r') col_edgebox1_vm1 = define_color(f.read()) f.close() f = open('edgebox1_vm2.txt', 'r') col_edgebox1_vm2 = define_color(f.read()) f.close() f = open('edgebox2.txt', 'r') col_edgebox2 = define_color(f.read()) f.close() f = open('edgebox2_vm1.txt', 'r') col_edgebox2_vm1 = define_color(f.read()) f.close() f = open('edgebox2_vm2.txt', 'r') col_edgebox2_vm2 = define_color(f.read()) f.close() f = open('edgebox2_vm3.txt', 'r') col_edgebox2_vm3 = define_color(f.read()) f.close() f = open('kube1.txt', 'r') col_kube1 = define_color(f.read()) f.close() f = open('kube2.txt', 'r') col_kube2 = define_color(f.read()) f.close() f = open('master.txt','r') col_master = define_color(f.read()) f.close() # input source for data - END fig = go.Figure(go.Sunburst( textfont = {"size":15}, labels=[" ","K-Fabric","K-Cube1","K-Cube2","K-Cube3","K-Cube4","K-Cube5","eno1","eno2","eno3","eno1 ","eno2 ","eno3 ","eno1 ","eno2 ","eno3 ","eno1 ","eno2 ","eno3 ","eno1 ","eno2 ","eno3 ","vSW1","vSW2","vSW3","VM1","VM2","VM3","vSW1 ","vSW2 ","vSW3 ","VM1 ","VM2 ","VM3 "],#9 # all the settings below probably follows the order of the labels above parents=[""," ","K-Fabric","K-Fabric","K-Fabric","K-Fabric","K-Fabric","K-Cube1","K-Cube1","K-Cube1","K-Cube2","K-Cube2","K-Cube2","K-Cube3","K-Cube3","K-Cube3","K-Cube4","K-Cube4","K-Cube4","K-Cube5","K-Cube5","K-Cube5","eno1 ","vSW1","vSW1","vSW3","vSW3","vSW2","eno1","vSW1 ","vSW1 ","vSW3 ","vSW3 ","vSW2 ",], # values = [BPF2, BPF3, BPF1] : BFP1 size doesn't really change marker = {"colors":[WHITE,WHITE,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,GRAY,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,], "line":{'color':[BLACK,BLACK,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,WHITE,]}}, # in the order of BPF2, BPF3 )) # set row / col here # fig.update_layout(grid=dict(columns=1,rows=1),margin = dict(t=0, l=0, r=0, b=0)) # maybe this is where they change the subplot f.close() return fig
def levels_visualization(data, levels_name): labels, parents, values, colors = generate_values_for_visualization(data, levels_name) trace = go.Sunburst(labels=labels, parents=parents, values=values, maxdepth = 2, branchvalues="total", textinfo="label", hoverinfo="value", textfont = {"size":16}, marker = {"line": {"width": 1}, "colors":colors}) layout = go.Layout(width=600, height=600, margin = go.layout.Margin(t=0, l=0, r=0, b=0)) return go.Figure([trace], layout)
def sunburst(countries=None): if countries: temp = data[data['Country'].isin(countries)] else: temp = data.copy() fig = px.sunburst(temp, path=['Department', 'Classification'], color_discrete_sequence=['#4a4bc7']) fig.update_traces(go.Sunburst(hovertemplate='Number of artworks=%{value}')) fig.update_layout( title=dict(text='Artworks Classification Arranged by Department', font=dict(color='black'))) return fig
def do_sunburst(html_flpth, png_flpth): logging.info('Generating sunburst') ana.TaxTree.build(app_file.get_fix_filtered_id2tax()) names, parents, counts, paths, color_ids = ana.TaxTree.get_sunburst_lists( ) # first el is Root palette = px.colors.qualitative.Alphabet id2ind = { color_id: i for i, color_id in enumerate( sorted(list(set(color_ids))) # deterministic unique color_ids ) } # map color ids to int colors = ['#FFFFFF'] + [ palette[id2ind[color_id] % len(palette)] for color_id in color_ids[1:] ] # Root is white fig = go.Figure( go.Sunburst( ids=paths, labels=names, parents=parents, values=counts, marker=dict(colors=colors), hovertemplate=( 'Taxon: %{label}<br>' 'Path: %{id}<br>' 'Amplicon count: %{value}' '<extra></extra>' # hide secondary hover box ), branchvalues='total', sort=False, )) fig.update_layout( title_text='Taxonomy (conf=%s)' % Var.params.get_prose_args()['conf'], title_x=0.5, ) fig.write_html(html_flpth) if DO_STATIC and len( names) * 4 > MAX_DATA: # whether to hide behind static image # 4 because name+path+count+color fig.write_image(png_flpth, width=IMG_HEIGHT, height=IMG_HEIGHT) return True else: return False
def sundata(): df_characters = pd.read_csv("data/character_data.csv") df_parent = pd.read_csv("data/parent_data.csv") parent_values = list(df_parent["parent"]) core_values = list(df_characters["Inner circle"].dropna()) environment_ecology = list(df_characters["Environment & Ecology"].dropna()) economy_technology = list(df_characters["Economy & Technology"].dropna()) social_values = list(df_characters["Social"].dropna()) species_values = list(df_characters["Species"].dropna()) parent=[""]+parent_values character= core_values+environment_ecology+economy_technology+social_values+species_values values = [values_birds_migration_route[-1],values_sea_and_archipelago_birds[-1],values_mussels[-1],values_fish[-1]] last_four = [] species_color = round(sum(values)/4) five_values = values five_values.append(species_color) print(five_values, " FIVE VALUS") for num in five_values: if num == 0: last_four.append("lightgrey") elif num == 1: last_four.append("red") elif num == 2: last_four.append("orange") elif num == 3: last_four.append("yellow") elif num == 4: last_four.append("lightgreen") elif num == 5: last_four.append("green") species_color = [last_four[-1]] last_four = last_four[0:4] colors_d = {"line": {"width":3},"colors":['lightgrey']*7+species_color+['lightgrey']*42+last_four} fig = go.Sunburst( labels=character, parents=parent, opacity=0.8, textfont = {'size': 15}, insidetextorientation = 'horizontal', marker = colors_d, ) layout = go.Layout(hovermode='closest', height=1300, width=1300,margin=go.layout.Margin(t=250, l=250, r=250, b=250)) values.clear() return {'data': [fig], 'layout': layout}
def _sunburst_os(db, output): print("Collecting data...") def generate_os_wrappers(): q = """SELECT os_response.value AS os, wrapper_response.flags AS wrapper_flags, wrapper_response.value AS wrapper_original, wrapper_sanitize.value AS wrapper_sanitized FROM responses os_response LEFT JOIN responses wrapper_response ON wrapper_response.question = 7 AND wrapper_response.session = os_response.session LEFT JOIN sanitize wrapper_sanitize ON wrapper_sanitize.idx = wrapper_response.idx WHERE os_response.question = 4;""" for result in iter_results(db, q): if result["wrapper_flags"] & ResponseFlags.sanitized: wrapper = result["wrapper_sanitized"] else: wrapper = result["wrapper_original"] yield result["os"], wrapper # ensure we count this for the case of the OS in general as well. if wrapper: yield result["os"], "" counter = collections.Counter() counter.update(generate_os_wrappers()) ids, labels, parents, values = [], [], [], [] for (os, wrapper), count in counter.items(): if wrapper: ids.append(f"{os} - {wrapper}") labels.append(wrapper) parents.append(os) values.append(count) else: ids.append(os) labels.append(os) parents.append("Preferred OS") values.append(count) print("Generating graph...") import plotly.graph_objects as go fig = go.Figure(data=go.Sunburst( ids=ids, labels=labels, parents=parents, values=values, branchvalues="total", hoverinfo="label+text+value+name+percent parent"), layout_title_text="OS and Wrapper Usage") _output_fig(fig, output)