Passing a Column Name in A Function2019 Community Moderator ElectionCalling a function of a module by using its name (a string)What's the difference between a method and a function?What is the naming convention in Python for variable and function names?var functionName = function() vs function functionName() Using global variables in a functionHow to make a chain of function decorators?Set a default parameter value for a JavaScript functionHow do I pass a variable by reference?What does the exclamation mark do before the function?Delete column from pandas DataFrame by column name

Did Amazon pay $0 in taxes last year?

How do you say "powers of ten"?

How can neutral atoms have exactly zero electric field when there is a difference in the positions of the charges?

Should I use HTTPS on a domain that will only be used for redirection?

Which sins are beyond punishment?

Is the NES controller port identical to the port on a Wii remote?

Would the melodic leap of the opening phrase of Mozart's K545 be considered dissonant?

Why use a Gaussian mixture model?

How to fix my table, centering of columns

Called into a meeting and told we are being made redundant (laid off) and "not to share outside". Can I tell my partner?

Are small insurances worth it

When was drinking water recognized as crucial in marathon running?

If there are any 3nion, 5nion, 7nion, 9nion, 10nion, etc.

Change only a specific Default Parameter on a function

Practical reasons to have both a large police force and bounty hunting network?

What could trigger powerful quakes on icy world?

What is better: yes / no radio, or simple checkbox?

Plagiarism of code by other PhD student

Is there a full canon version of Tyrion's jackass/honeycomb joke?

Can I cast a spell through the Invoke Duplicity clone while inside a Forcecage?

How can I handle a player who pre-plans arguments about my rulings on RAW?

How to kill a localhost:8080

Create chunks from an array

Is there a hobbyist standard for Trains track modules?



Passing a Column Name in A Function



2019 Community Moderator ElectionCalling a function of a module by using its name (a string)What's the difference between a method and a function?What is the naming convention in Python for variable and function names?var functionName = function() vs function functionName() Using global variables in a functionHow to make a chain of function decorators?Set a default parameter value for a JavaScript functionHow do I pass a variable by reference?What does the exclamation mark do before the function?Delete column from pandas DataFrame by column name










0















Hi I am currently trying to construct a scatter plot on python dash where I can connect a dropdown (consisting of different column names) to the scatter plot. Therefore when I change the value of the dropdown the scatterplot will show different values dependent on the value of the dropdown. However, my issue is that a column name is intrinsically a string and the dropdown consists of a dictionary of these values making it hard to pass through. This is the code I have right now:



html.Div([dcc.Dropdown(
id='mood',
options=[
'label': 'Positive', 'value': 'Positive',
'label': 'Negative', 'value': 'Negative',
'label': 'Compound', 'value': 'Compound'],
value='Compound')], style='width':'15%'
),
html.Div([
dcc.Graph(id='linear')]),
html.Div([
dcc.Graph(id='linear2')])
])

@app.callback(
dash.dependencies.Output('linear','figure'),
[dash.dependencies.Input('mood','value')])

def update_graph(mood_name):
y=file.get(column) ==mood_name]
scatter=go.scatter(y=y,marker=dict(
color='rgb(0,191,255)', # code for sky blue 0,191,255
line=dict(
color='rgb(8,48,107)',
width=1.5,
)),opacity=0.6,name='Sentiment')
layout=go.Layout(xaxis='title': 'Tweets',
yaxis='title': 'Polarity',
title= 'Tweets',
hovermode='closest')
return 'data':[scatter],
'layout':[layout]


The def update graph function is where I am having trouble passing through these column names (positive, negative and compound). Any help would be greatly appreciated, thanks!










share|improve this question


























    0















    Hi I am currently trying to construct a scatter plot on python dash where I can connect a dropdown (consisting of different column names) to the scatter plot. Therefore when I change the value of the dropdown the scatterplot will show different values dependent on the value of the dropdown. However, my issue is that a column name is intrinsically a string and the dropdown consists of a dictionary of these values making it hard to pass through. This is the code I have right now:



    html.Div([dcc.Dropdown(
    id='mood',
    options=[
    'label': 'Positive', 'value': 'Positive',
    'label': 'Negative', 'value': 'Negative',
    'label': 'Compound', 'value': 'Compound'],
    value='Compound')], style='width':'15%'
    ),
    html.Div([
    dcc.Graph(id='linear')]),
    html.Div([
    dcc.Graph(id='linear2')])
    ])

    @app.callback(
    dash.dependencies.Output('linear','figure'),
    [dash.dependencies.Input('mood','value')])

    def update_graph(mood_name):
    y=file.get(column) ==mood_name]
    scatter=go.scatter(y=y,marker=dict(
    color='rgb(0,191,255)', # code for sky blue 0,191,255
    line=dict(
    color='rgb(8,48,107)',
    width=1.5,
    )),opacity=0.6,name='Sentiment')
    layout=go.Layout(xaxis='title': 'Tweets',
    yaxis='title': 'Polarity',
    title= 'Tweets',
    hovermode='closest')
    return 'data':[scatter],
    'layout':[layout]


    The def update graph function is where I am having trouble passing through these column names (positive, negative and compound). Any help would be greatly appreciated, thanks!










    share|improve this question
























      0












      0








      0








      Hi I am currently trying to construct a scatter plot on python dash where I can connect a dropdown (consisting of different column names) to the scatter plot. Therefore when I change the value of the dropdown the scatterplot will show different values dependent on the value of the dropdown. However, my issue is that a column name is intrinsically a string and the dropdown consists of a dictionary of these values making it hard to pass through. This is the code I have right now:



      html.Div([dcc.Dropdown(
      id='mood',
      options=[
      'label': 'Positive', 'value': 'Positive',
      'label': 'Negative', 'value': 'Negative',
      'label': 'Compound', 'value': 'Compound'],
      value='Compound')], style='width':'15%'
      ),
      html.Div([
      dcc.Graph(id='linear')]),
      html.Div([
      dcc.Graph(id='linear2')])
      ])

      @app.callback(
      dash.dependencies.Output('linear','figure'),
      [dash.dependencies.Input('mood','value')])

      def update_graph(mood_name):
      y=file.get(column) ==mood_name]
      scatter=go.scatter(y=y,marker=dict(
      color='rgb(0,191,255)', # code for sky blue 0,191,255
      line=dict(
      color='rgb(8,48,107)',
      width=1.5,
      )),opacity=0.6,name='Sentiment')
      layout=go.Layout(xaxis='title': 'Tweets',
      yaxis='title': 'Polarity',
      title= 'Tweets',
      hovermode='closest')
      return 'data':[scatter],
      'layout':[layout]


      The def update graph function is where I am having trouble passing through these column names (positive, negative and compound). Any help would be greatly appreciated, thanks!










      share|improve this question














      Hi I am currently trying to construct a scatter plot on python dash where I can connect a dropdown (consisting of different column names) to the scatter plot. Therefore when I change the value of the dropdown the scatterplot will show different values dependent on the value of the dropdown. However, my issue is that a column name is intrinsically a string and the dropdown consists of a dictionary of these values making it hard to pass through. This is the code I have right now:



      html.Div([dcc.Dropdown(
      id='mood',
      options=[
      'label': 'Positive', 'value': 'Positive',
      'label': 'Negative', 'value': 'Negative',
      'label': 'Compound', 'value': 'Compound'],
      value='Compound')], style='width':'15%'
      ),
      html.Div([
      dcc.Graph(id='linear')]),
      html.Div([
      dcc.Graph(id='linear2')])
      ])

      @app.callback(
      dash.dependencies.Output('linear','figure'),
      [dash.dependencies.Input('mood','value')])

      def update_graph(mood_name):
      y=file.get(column) ==mood_name]
      scatter=go.scatter(y=y,marker=dict(
      color='rgb(0,191,255)', # code for sky blue 0,191,255
      line=dict(
      color='rgb(8,48,107)',
      width=1.5,
      )),opacity=0.6,name='Sentiment')
      layout=go.Layout(xaxis='title': 'Tweets',
      yaxis='title': 'Polarity',
      title= 'Tweets',
      hovermode='closest')
      return 'data':[scatter],
      'layout':[layout]


      The def update graph function is where I am having trouble passing through these column names (positive, negative and compound). Any help would be greatly appreciated, thanks!







      python function callback plotly plotly-dash






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked yesterday









      SamSam

      32




      32






















          1 Answer
          1






          active

          oldest

          votes


















          0














          Maybe you selected wrong when filter dataframe by value provided from dropdown.
          Code:



          from flask import Flask
          import dash
          import dash_core_components as dcc
          import dash_html_components as html
          from dash.dependencies import Input, Output
          import pandas as pd
          import plotly
          import plotly.graph_objs as go

          server = Flask(__name__)
          app = dash.Dash(server=server)
          df = pd.DataFrame("Pos": [4, 5, 7, 8],
          "Neg": [3, 6, 8, 9],
          "Compound": [7, 11, 15, 17],
          "values": [1, 2, 3, 4])
          app.layout = html.Div(
          [
          html.H1("Scatter with dropdown"),
          dcc.Dropdown(
          id='dropdown',
          options=['label': 'Pos', 'value': 'Pos',
          'label': 'Neg', 'value': 'Neg',
          'label': 'Compound', 'value': 'Compound'],
          value='Compound'
          ),
          html.Div(id='scatter'),
          ])


          @app.callback(
          Output("scatter", "children"),
          [Input("dropdown", "value")],
          )
          def change_scatter(value):
          """Change scatter according to dropdown."""
          global df
          dff = df[['values', value]]
          return html.Div(dcc.Graph(
          id='scatter-plot',
          figure=
          'data': [

          'x': dff['values'],
          'y': dff[value],
          'type': 'scatter',
          # 'text': dff[value],
          'name': value

          ],
          'layout':
          'xaxis': 'title': 'Position',
          'yaxis': 'title': 'Values',


          ))


          if __name__ == "__main__":
          app.run_server(debug=True, port=8888)


          Output:
          Scatter with dropdown
          Hope this example helps you found a mistake






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55006570%2fpassing-a-column-name-in-a-function%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Maybe you selected wrong when filter dataframe by value provided from dropdown.
            Code:



            from flask import Flask
            import dash
            import dash_core_components as dcc
            import dash_html_components as html
            from dash.dependencies import Input, Output
            import pandas as pd
            import plotly
            import plotly.graph_objs as go

            server = Flask(__name__)
            app = dash.Dash(server=server)
            df = pd.DataFrame("Pos": [4, 5, 7, 8],
            "Neg": [3, 6, 8, 9],
            "Compound": [7, 11, 15, 17],
            "values": [1, 2, 3, 4])
            app.layout = html.Div(
            [
            html.H1("Scatter with dropdown"),
            dcc.Dropdown(
            id='dropdown',
            options=['label': 'Pos', 'value': 'Pos',
            'label': 'Neg', 'value': 'Neg',
            'label': 'Compound', 'value': 'Compound'],
            value='Compound'
            ),
            html.Div(id='scatter'),
            ])


            @app.callback(
            Output("scatter", "children"),
            [Input("dropdown", "value")],
            )
            def change_scatter(value):
            """Change scatter according to dropdown."""
            global df
            dff = df[['values', value]]
            return html.Div(dcc.Graph(
            id='scatter-plot',
            figure=
            'data': [

            'x': dff['values'],
            'y': dff[value],
            'type': 'scatter',
            # 'text': dff[value],
            'name': value

            ],
            'layout':
            'xaxis': 'title': 'Position',
            'yaxis': 'title': 'Values',


            ))


            if __name__ == "__main__":
            app.run_server(debug=True, port=8888)


            Output:
            Scatter with dropdown
            Hope this example helps you found a mistake






            share|improve this answer



























              0














              Maybe you selected wrong when filter dataframe by value provided from dropdown.
              Code:



              from flask import Flask
              import dash
              import dash_core_components as dcc
              import dash_html_components as html
              from dash.dependencies import Input, Output
              import pandas as pd
              import plotly
              import plotly.graph_objs as go

              server = Flask(__name__)
              app = dash.Dash(server=server)
              df = pd.DataFrame("Pos": [4, 5, 7, 8],
              "Neg": [3, 6, 8, 9],
              "Compound": [7, 11, 15, 17],
              "values": [1, 2, 3, 4])
              app.layout = html.Div(
              [
              html.H1("Scatter with dropdown"),
              dcc.Dropdown(
              id='dropdown',
              options=['label': 'Pos', 'value': 'Pos',
              'label': 'Neg', 'value': 'Neg',
              'label': 'Compound', 'value': 'Compound'],
              value='Compound'
              ),
              html.Div(id='scatter'),
              ])


              @app.callback(
              Output("scatter", "children"),
              [Input("dropdown", "value")],
              )
              def change_scatter(value):
              """Change scatter according to dropdown."""
              global df
              dff = df[['values', value]]
              return html.Div(dcc.Graph(
              id='scatter-plot',
              figure=
              'data': [

              'x': dff['values'],
              'y': dff[value],
              'type': 'scatter',
              # 'text': dff[value],
              'name': value

              ],
              'layout':
              'xaxis': 'title': 'Position',
              'yaxis': 'title': 'Values',


              ))


              if __name__ == "__main__":
              app.run_server(debug=True, port=8888)


              Output:
              Scatter with dropdown
              Hope this example helps you found a mistake






              share|improve this answer

























                0












                0








                0







                Maybe you selected wrong when filter dataframe by value provided from dropdown.
                Code:



                from flask import Flask
                import dash
                import dash_core_components as dcc
                import dash_html_components as html
                from dash.dependencies import Input, Output
                import pandas as pd
                import plotly
                import plotly.graph_objs as go

                server = Flask(__name__)
                app = dash.Dash(server=server)
                df = pd.DataFrame("Pos": [4, 5, 7, 8],
                "Neg": [3, 6, 8, 9],
                "Compound": [7, 11, 15, 17],
                "values": [1, 2, 3, 4])
                app.layout = html.Div(
                [
                html.H1("Scatter with dropdown"),
                dcc.Dropdown(
                id='dropdown',
                options=['label': 'Pos', 'value': 'Pos',
                'label': 'Neg', 'value': 'Neg',
                'label': 'Compound', 'value': 'Compound'],
                value='Compound'
                ),
                html.Div(id='scatter'),
                ])


                @app.callback(
                Output("scatter", "children"),
                [Input("dropdown", "value")],
                )
                def change_scatter(value):
                """Change scatter according to dropdown."""
                global df
                dff = df[['values', value]]
                return html.Div(dcc.Graph(
                id='scatter-plot',
                figure=
                'data': [

                'x': dff['values'],
                'y': dff[value],
                'type': 'scatter',
                # 'text': dff[value],
                'name': value

                ],
                'layout':
                'xaxis': 'title': 'Position',
                'yaxis': 'title': 'Values',


                ))


                if __name__ == "__main__":
                app.run_server(debug=True, port=8888)


                Output:
                Scatter with dropdown
                Hope this example helps you found a mistake






                share|improve this answer













                Maybe you selected wrong when filter dataframe by value provided from dropdown.
                Code:



                from flask import Flask
                import dash
                import dash_core_components as dcc
                import dash_html_components as html
                from dash.dependencies import Input, Output
                import pandas as pd
                import plotly
                import plotly.graph_objs as go

                server = Flask(__name__)
                app = dash.Dash(server=server)
                df = pd.DataFrame("Pos": [4, 5, 7, 8],
                "Neg": [3, 6, 8, 9],
                "Compound": [7, 11, 15, 17],
                "values": [1, 2, 3, 4])
                app.layout = html.Div(
                [
                html.H1("Scatter with dropdown"),
                dcc.Dropdown(
                id='dropdown',
                options=['label': 'Pos', 'value': 'Pos',
                'label': 'Neg', 'value': 'Neg',
                'label': 'Compound', 'value': 'Compound'],
                value='Compound'
                ),
                html.Div(id='scatter'),
                ])


                @app.callback(
                Output("scatter", "children"),
                [Input("dropdown", "value")],
                )
                def change_scatter(value):
                """Change scatter according to dropdown."""
                global df
                dff = df[['values', value]]
                return html.Div(dcc.Graph(
                id='scatter-plot',
                figure=
                'data': [

                'x': dff['values'],
                'y': dff[value],
                'type': 'scatter',
                # 'text': dff[value],
                'name': value

                ],
                'layout':
                'xaxis': 'title': 'Position',
                'yaxis': 'title': 'Values',


                ))


                if __name__ == "__main__":
                app.run_server(debug=True, port=8888)


                Output:
                Scatter with dropdown
                Hope this example helps you found a mistake







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 6 hours ago









                OysiylOysiyl

                705311




                705311





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55006570%2fpassing-a-column-name-in-a-function%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                    Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                    How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page