首页 > 解决方案 > 在 for 循环中向 Plotly Graph 添加跟踪,仅显示循环中的最后一个跟踪

问题描述

我正在尝试为搜索到的人类基因的每个同义词名称添加痕迹,但是当我在应用程序中搜索基因时,它只显示搜索到的基因和同义词列表中的最后一个基因。我不确定如何能够看到以相同颜色绘制的所有同义词基因以及搜索的基因?

当前代码:

import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.io as pio
from plotly.tools import make_subplots
pd.options.plotting.backend = "plotly"
pio.renderers.default = "browser"


try:
        app = dash.Dash(__name__)
    
        app.layout = html.Div([
            html.Label('Search Box'),
        dcc.Input(id="search_gene", 
                  type="text",
                  value = '',
                  placeholder="Type a human gene name",
                  debounce = True,
                  minLength = 0, maxLength = 50,
                  autoComplete='on',
                  size='40'),            
        html.Br(),
        html.Div([
            html.Div([
            dcc.Graph(id='mygraph')])])    
        ])           
                              
        @app.callback(
            Output('mygraph', 'figure'),
            [Input('search_gene', 'value')])
        def update_output(search_gene):
            df = pd.read_csv('list_out.txt', sep = '\t', dtype=str)
            df = df.transpose().reset_index().rename(columns={'index':'Date'})
            new_header = df.iloc[0] 
            df = df[1:] 
            df.columns = new_header
            df = df.iloc[0:600]
            df = df.set_index('Date')

            
            lookup_df = pd.read_csv('Gene_Lookup.csv', dtype = str)
            link = lookup_df.set_index('Approved_Symbol').Linked_Genes.str.split('|').to_dict()
            
            link_date = lookup_df.set_index('Approved_Symbol').Date_Name_Changed.to_dict()
            
            
            if search_gene:
                search_gene = (search_gene).upper()
                syns = link[search_gene]
                date = link_date[search_gene]
                
                
                trace1 = go.Scatter(x=df.index, 
                                    y = df[search_gene], 
                                    line_shape='linear', 
                                    line = dict(color='steelblue'), 
                                    name = search_gene)
               
                    
                fig = make_subplots(rows=1,subplot_titles=['Synonymous Gene Names'],
                shared_yaxes=True)
                
                fig.add_trace(trace1)
                
                for i in syns:
                    fig.append_trace(go.Scatter(x=df.index, 
                                    y = df[i], 
                                    line_shape='linear', 
                                    line = dict(color='black'), 
                                    name = i), row=1, col=1)
                
                fig.update_layout(title="Human Gene Name Occurances Per Month", xaxis_title="Date", yaxis_title="Count")
                fig.add_shape(type="line", name = 'Date Human Genome Sequenced',
                              x0='2003-4', y0= '-10', x1='2003-4', y1=100,
                              line=dict(color="lightblue",width=3))
                fig.add_shape(type="line", name = 'Date Name Changed',
                              x0=date, y0='-10', x1=date, y1=100,
                              line=dict(color="darkblue",width=3))
                    
            elif search_gene is None or len(search_gene) == 0:
                df1 = pd.read_csv('list_out1.txt', sep='\t', dtype=str)
                #df1 = df1.set_index('Date')
                fig = px.line(df1, x=df1['Date'], y=df1.columns[1:])
                fig.update_layout(title="Human Gene Name Occurances Per Month", xaxis_title="Date", yaxis_title="Count")
                
            return fig
                    
                
        if __name__ == '__main__':
            app.run_server(debug=True)

except:
    pass

绘制的数据(df):

        BNaC2 ASIC1 hBNaC2
Time                    
1971-1      0     0    0
1971-2      0     3    0
1971-3      0     0    0
2017-9      1     0    0
2017-10     0     4    0
2017-11     0     0    7
2017-12     5     0    0

基因查找文件:

      Approved_Symbol  ...            Linked_Genes
0              A12M1~  ...                     NaN
1             A2MRAP~  ...                     NaN
2               ASIC1  ...      ACCN2|BNaC2|hBNaC2
3               BNaC2  ...      ACCN2|ASIC1|hBNaC2
4              hBNaC2  ...       ACCN2|ASIC1|BNaC2

标签: pythonplotly

解决方案


推荐阅读