def test_dbcl007_hidden_labels(dash_duo): app = dash.Dash(__name__) data = _mtcars_data row_labels = list(_mtcars_data.index) col_labels = list(_mtcars_data.columns) app.layout = html.Div( nested_component_layout( dash_bio.Clustergram(data=data, row_labels=row_labels, column_labels=col_labels))) nested_component_app_callback( app, dash_duo, component=dash_bio.Clustergram, component_data=data, test_prop_name="hidden_labels", test_prop_value="row", prop_value_type="string", ) # ensure that row labels are hidden assert len(dash_duo.find_elements("g.yaxislayer-above g.y5tick")) == 0 # ensure that column labels are displayed assert len(dash_duo.find_elements("g.xaxislayer-above g.x5tick")) == len( col_labels) # create a new instance of the app to test hiding of column labels app = dash.Dash(__name__) app.layout = html.Div( nested_component_layout( dash_bio.Clustergram(data=data, row_labels=row_labels, column_labels=col_labels))) nested_component_app_callback( app, dash_duo, component=dash_bio.Clustergram, component_data=data, test_prop_name="hidden_labels", test_prop_value="col", prop_value_type="string", ) # ensure that column labels are hidden assert len(dash_duo.find_elements("g.xaxislayer-above g.x5tick")) == 0 # ensure that row labels are displayed assert len(dash_duo.find_elements("g.yaxislayer-above g.y5tick")) == len( row_labels)
def update_clustergram(type="Microarray"): """ """ if type is "Microarray": df = pd.read_excel(muArrayFile, index_col=0) df = df.fillna(0) else: df = pd.read_csv(gcpFile, index_col=0) df = df.fillna(0) ccl = df.index.to_list() feat = list(df.columns.values) return { dcc.Graph(figure=dashbio.Clustergram( data=df.values #row_labels=ccl, #column_labels=feat, #height=800, #width=700 #col_group_marker=[ # {'group': 1, 'annotation': 'largest column cluster', 'color': '#EF553B'} #], #row_group_marker=[ # {'group': 2, 'annotation': 'cluster 2', 'color': '#AB63FA'}, # {'group': 1, 'annotation': '', 'color': '#19D3F3'} #] )) }
def test_dbcl003_row_col_thresholds(dash_duo): app = dash.Dash(__name__) app.layout = html.Div( nested_component_layout(dash_bio.Clustergram(data=_data))) nested_component_app_callback( app, dash_duo, component=dash_bio.Clustergram, component_data=_data, test_prop_name="color_threshold", test_prop_value=json.dumps({ "row": 250, "col": 700 }), prop_value_type="dict", take_snapshot=True, ) # there should be 9 traces for the column dendrogram # plus one trace for the background assert len( dash_duo.find_elements( "g.subplot.x2y2 > g.plot g.trace.scatter")) == 10 # 30 traces for the row dendrogram, plus one for the background assert len( dash_duo.find_elements( "g.subplot.x4y4 > g.plot g.trace.scatter")) == 31
def update_clustergram(gnps_task): quant_df = _get_quant_df(gnps_task) filename_headers = [ header for header in quant_df.columns if "Peak area" in header ] values_df = quant_df[filename_headers] values_df = values_df.clip(1) feature_labels = list(quant_df["row ID"]) color_palette = ['rgb(128, 0, 96)', 'rgb(230, 115, 0)', 'rgb(255, 191, 0)'] fig = dashbio.Clustergram( data=values_df.values, column_labels=filename_headers, row_labels=feature_labels, color_map=[[0.0, color_palette[0]], [0.5, color_palette[1]], [1.0, color_palette[2]]], color_list={ 'row': [color_palette[0], color_palette[1], color_palette[2]], 'col': [color_palette[1], color_palette[2], color_palette[0]], 'bg': 'rgb(255,255,255)' }, height=800, width=700, optimal_leaf_order=False, center_values=True, log_transform=True, line_width=2) fig.update_layout(yaxis2={'domain': [0.74, 1]}) return dcc.Graph(figure=fig)
def test_dbcl005_row_annotations(dash_duo): app = dash.Dash(__name__) app.layout = html.Div(nested_component_layout( dash_bio.Clustergram( data=_data ) )) nested_component_app_callback( app, dash_duo, component=dash_bio.Clustergram, component_data=_data, test_prop_name='row_group_marker', test_prop_value=json.dumps( [{'group': 2, 'annotation': 'cluster two', 'color': 'rgb(248, 62, 199)'}]), extra_props={'color_threshold': {'row': 250, 'col': 700}}, prop_value_type='list', take_snapshot=True ) # the annotation has shown up assert len(dash_duo.find_elements('g.subplot.x6y6')) == 1 # the annotation is the correct color dash_duo.wait_for_style_to_equal( 'g.subplot.x6y6 g.plot g.lines > path', 'stroke', 'rgb(248, 62, 199)')
def test_dbcl005_row_annotations(dash_duo): app = dash.Dash(__name__) app.layout = html.Div( nested_component_layout(dash_bio.Clustergram(data=_data))) nested_component_app_callback( app, dash_duo, component=dash_bio.Clustergram, component_data=_data, test_prop_name="row_group_marker", test_prop_value=json.dumps([{ "group": 2, "annotation": "cluster two", "color": "rgb(248, 62, 199)" }]), extra_props={"color_threshold": { "row": 250, "col": 700 }}, prop_value_type="list", take_snapshot=True, ) # the annotation has shown up assert len(dash_duo.find_elements("g.subplot.x6y6")) == 1 # the annotation is the correct color dash_duo.wait_for_style_to_equal("g.subplot.x6y6 g.plot g.lines > path", "stroke", "rgb(248, 62, 199)")
def test_dbcl003_row_col_thresholds(dash_duo): app = dash.Dash(__name__) app.layout = html.Div(nested_component_layout( dash_bio.Clustergram( data=_data ) )) nested_component_app_callback( app, dash_duo, component=dash_bio.Clustergram, component_data=_data, test_prop_name='color_threshold', test_prop_value=json.dumps({'row': 250, 'col': 700}), prop_value_type='dict', take_snapshot=True ) # there should be two clusters, i.e., two traces, for the column dendrogram # plus one trace for the background assert len(dash_duo.find_elements( 'g.subplot.x2y2 > g.plot g.trace.scatter')) == 3 # three clusters for the row dendrogram, plus one for the background assert len(dash_duo.find_elements( 'g.subplot.x4y4 > g.plot g.trace.scatter')) == 4
def test_dbcl002_cluster_by_row_or_col(dash_duo): app = dash.Dash(__name__) app.layout = html.Div(nested_component_layout( dash_bio.Clustergram( data=_data ) )) nested_component_app_callback( app, dash_duo, component=dash_bio.Clustergram, component_data=_data, test_prop_name='cluster', test_prop_value='row', prop_value_type='string' ) assert len(dash_duo.find_elements('g.subplot.x2y2')) == 0 assert len(dash_duo.find_elements('g.subplot.x4y4')) == 1 # create a new instance of the app to test column clustering app = dash.Dash(__name__) app.layout = html.Div(nested_component_layout( dash_bio.Clustergram( data=_data ) )) nested_component_app_callback( app, dash_duo, component=dash_bio.Clustergram, component_data=_data, test_prop_name='cluster', test_prop_value='col', prop_value_type='string', take_snapshot=True ) assert len(dash_duo.find_elements('g.subplot.x4y4')) == 0 assert len(dash_duo.find_elements('g.subplot.x2y2')) == 1
def display_clustergram(_, group_markers, selRows, selCols, fig_opts, dataset_name, contents, filename, rowLabelsSource): if (len(selRows) < 2 or len(selCols) < 2 or fig_opts is None): return html.Div( 'No data have been selected to display. Please upload a file \ or select a preloaded file from the dropdown, then select at \ least two columns and two rows.', style={ 'padding': '30px', 'font-size': '20pt' }) if dataset_name is not None: dataset = datasets[dataset_name] data, _, _, _ = \ geneExpressionReader.parse_tsv( filepath=dataset['file'], rowLabelsSource=dataset['rowLabelsSource'], headerRows=dataset['headerRows'], headerCols=dataset['headerCols'], rows=selRows, columns=selCols ) elif contents is not None and dataset_name is None: content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string).decode('UTF-8') if rowLabelsSource is None: rowLabelsSource = 'Gene Name' data, _, _, _ = \ geneExpressionReader.parse_tsv( contents=decoded, rowLabelsSource=rowLabelsSource, rows=selRows, columns=selCols ) if group_markers is not None: fig_opts['rowGroupMarker'] = group_markers['rowGroupMarker'] fig_opts['colGroupMarker'] = group_markers['colGroupMarker'] try: fig, _ = dash_bio.Clustergram(computed_traces=None, data=data, **fig_opts) return dcc.Graph(id='clustergram', figure=fig) except Exception as e: return "There was an error: {}.".format(e)
def update_clustergram(rows): if len(rows) < 2: return "Please select at least two rows to display." return dcc.Graph(figure=dashbio.Clustergram(data=df.loc[rows].values, column_labels=columns, row_labels=rows, color_threshold={ 'row': 250, 'col': 700 }, hidden_labels='row', height=800, width=700))
def test_dbcl001_colorscale(dash_duo): app = dash.Dash(__name__) app.layout = html.Div( nested_component_layout(dash_bio.Clustergram(data=_data))) nested_component_app_callback( app, dash_duo, component=dash_bio.Clustergram, component_data=_data, test_prop_name='color_map', test_prop_value=json.dumps([[0, 'blue'], [0.5, 'yellow'], [1, 'pink']]), prop_value_type='list', path_to_test_prop='["data"][2]["colorscale"]', take_snapshot=True)
def test_dbcl001_colorscale(dash_duo): app = dash.Dash(__name__) app.layout = html.Div( nested_component_layout(dash_bio.Clustergram(data=_data))) nested_component_app_callback( app, dash_duo, component=dash_bio.Clustergram, component_data=_data, test_prop_name="color_map", test_prop_value=json.dumps([[0, "blue"], [0.5, "yellow"], [1, "pink"]]), prop_value_type="list", path_to_test_prop='["data"][41]["colorscale"]', take_snapshot=True, )
def test_dbcl006_df_input_row_cluster(dash_duo): app = dash.Dash(__name__) # run the same test as dbcl002 (row clustering) where table of # observations (data argument) is left as a DataFrame assert isinstance(_mtcars_data, pd.DataFrame) app.layout = html.Div( nested_component_layout(dash_bio.Clustergram(data=_mtcars_data))) nested_component_app_callback(app, dash_duo, component=dash_bio.Clustergram, component_data=_data, test_prop_name='cluster', test_prop_value='row', prop_value_type='string') assert len(dash_duo.find_elements('g.subplot.x2y2')) == 0 assert len(dash_duo.find_elements('g.subplot.x4y4')) == 1
import dash_html_components as html import dash_core_components as dcc import dash_bio as dashbio import base64 import pandas as pd # copy docs code here df = pd.read_csv('https://raw.githubusercontent.com/plotly/dash-bio/master/tests/dashbio_demos/dash-clustergram/data/mtcars.tsv', sep=' ', skiprows=4).set_index('model') data = df.values component = dcc.Graph(figure=dashbio.Clustergram( data=data, column_labels=list(df.columns.values), color_threshold={'row': 150, 'col': 700}, row_labels=list(df.index), hidden_labels=['row'], height=800, width=600 )) component_image = html.Img( src='data:image/png;base64,{}'.format( base64.b64encode( open( './images/pic_clustergram.png', 'rb' ).read() ).decode() ), style={'width': '600px'} )
import dash import dash_bio as dashbio import dash_core_components as dcc import dash_html_components as html import plotly iris = plotly.data.iris() iris = iris.drop("species", 1) app = dash.Dash(__name__) app.layout = html.Div([ dcc.Graph(figure=dashbio.Clustergram( data=iris.values, # ➊ グラフ作成に用いる値の設定 column_labels=list(iris.columns.values), # ➋ 列ラベルの設定 width=800, # ➋ 横幅の設定 height=800, # ➋ 高さの設定 # ➋ ヒートマップの配色 color_map=[[0.0, "white"], [0.5, "gray"], [1.0, "black"]], # ➋ デントログラムの高さの設定(行側、列側、ヒートマップ比) display_ratio=[0.3, 0.1], )) ]) if __name__ == "__main__": app.run_server(debug=True)
def display_clustergram(_, group_markers, sel_rows, sel_cols, fig_opts, dataset_name, contents, filename, computed_traces): ctx = dash.callback_context adding_grp_marker = ctx.triggered[0]['prop_id'].split( '.')[0] == 'group-markers' wrapper_content = '' curves = None comp_traces = computed_traces if len(sel_rows) < 2 or len(sel_cols) < 2 and \ dataset_name is None and contents is None: wrapper_content = html.Div( 'No data have been selected to display. Please upload a file \ or select a preloaded file from the dropdown, then select at \ least two columns and two rows.', style={ 'padding': '40px', 'font-size': '20pt' }) return wrapper_content, curves, comp_traces if fig_opts['cluster'] is None or len(fig_opts['cluster']) == 0: wrapper_content = html.Div( 'No dimension has been selected along which to perform \ clustering. \ Please select at least one option from the dropdown.', style={ 'padding': '30px', 'font-size': '20pt' }) return wrapper_content, curves, comp_traces if dataset_name is not None: dataset = datasets[dataset_name] if dataset['file'].endswith('.tsv'): data = gene_expression_reader.read_tsv_file( filepath=dataset['file'], rows=sel_rows, columns=sel_cols, ignore_columns=dataset['ignore_columns'], index_column=dataset['row_labels_source'], return_filtered_data=True) elif dataset['file'].endswith('.soft'): data = gene_expression_reader.read_soft_file( filepath=dataset['file'], rows=sel_rows, columns=sel_cols, return_filtered_data=True) elif contents is not None and dataset_name is None: content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string).decode('UTF-8') try: data = gene_expression_reader.read_soft_file( contents=decoded, rows=sel_rows, columns=sel_cols, return_filtered_data=True) except Exception: data = None if group_markers is not None: fig_opts['row_group_marker'] = group_markers['row_group_marker'] fig_opts['col_group_marker'] = group_markers['col_group_marker'] try: # don't recompute the dendrogram traces if we're just adding a group # marker if adding_grp_marker and computed_traces is not None: fig, curves = dash_bio.Clustergram( generate_curves_dict=True, computed_traces=computed_traces, data=data, **fig_opts) else: fig, curves, comp_traces = dash_bio.Clustergram( generate_curves_dict=True, return_computed_traces=True, data=data, **fig_opts) wrapper_content = dcc.Graph(id='clustergram', figure=fig) except IndexError: wrapper_content = "Loading data..." except ValueError: wrapper_content = "Loading data..." except Exception as e: wrapper_content = "There was an error: {}".format(e) return wrapper_content, curves, comp_traces
#! -*- utf-8 -*- import pandas as pd import dash_core_components as dcc import dash_bio as dashbio import plotly.subplots df = pd.read_csv( 'https://raw.githubusercontent.com/plotly/dash-bio/master/tests/dashbio_demos/sample_data/clustergram_mtcars.tsv', sep='\t', skiprows=4).set_index('model') columns = list(df.columns.values) rows = list(df.index) clustergram = dashbio.Clustergram(data=df.loc[rows].values, row_labels=rows, column_labels=columns, color_threshold={ 'row': 250, 'col': 700 }, height=800, width=700, display_ratio=[0.1, 0.7]) print(dcc.Graph(figure=clustergram))
import pandas as pd import dash_core_components as dcc import dash_bio as dashbio import warnings df = pd.read_csv( 'https://raw.githubusercontent.com/plotly/dash-bio/master/tests/dashbio_demos/sample_data/clustergram_mtcars.tsv', sep='\t', skiprows=4).set_index('model') columns = list(df.columns.values) rows = list(df.index) clustergram = dashbio.Clustergram(data=df.loc[rows].values, row_labels=rows, column_labels=columns, color_threshold={ 'row': 250, 'col': 700 }, height=800, width=700, color_list={ 'row': ['#636EFA', '#00CC96', '#19D3F3'], 'col': ['#AB63FA', '#EF553B'], 'bg': '#506784' }, line_width=2) print(dcc.Graph(figure=clustergram)) # dcc.Graph(figure=clustergram)
]), label="3D protein", ), dbc.Tab( dcc.Graph(figure=dashbio.Clustergram( data=data, hidden_labels=["row"], height=900, width=1400, column_labels=list(df.columns.values), row_labels=list(df.index), color_threshold={ "row": 150, "col": 700 }, color_map=[ [0.0, color_palette[0]], [0.5, color_palette[1]], [1.0, color_palette[2]], ], color_list={ "row": [color_palette[0], color_palette[1], color_palette[2]], "col": [color_palette[1], color_palette[2], color_palette[0]], "bg": "rgb(255,255,255)", }, annotation_font=dict(color="white", size=10), tick_font=dict(size=15, color="rgb(200,200,200)"), )), label="Microarray Heatmap", ), ])