Python: Run Dash in the terminal, pyenv, pyenv-virtualenv ver. 2

Last Updated on September 15, 2022 by shibatau

I. What shall we learn?

We will learn how to create interactive charts with Dash on the browser through the terminal.

You can learn Dash and the scripts here:

Don’t Just Create Plots in Python, Go One Step Beyond

II. Creating a virtual environment with Pyenv and Pyenv-virtualenv

1.Creating a virtual environment

You can learn how to create a virtual environment with Pyenv and Pyenv-virtualenv here:

How to use Pyenv + Pyenv-vertualenv

2.Creating a directory for the project

Run the command in the directory where you want to create a project directory:

mkdir YOURPROJECTNAME && cd YOURPROJECTNAME

Assign the virtual environment created at 1 to the directory where you are:

pyenv local YOURPROJECTNAME

Install libraries with pip.

III. Run the Python file in the terminal

layout-final.py:

import dash
import dash_html_components as html
from dash import dcc
import plotly.graph_objects as go
import dash_bootstrap_components as dbc
from pytrends.request import TrendReq


pytrend = TrendReq()

pytrend.build_payload(kw_list=["Netflix"])
# Interest by Region
df = pytrend.interest_by_region()
int_by_reg = df['Netflix'].sort_values(ascending = False).head(10)

int_by_reg =int_by_reg.reset_index()
int_by_reg.columns = ['Country','Score']

# ## Related Topics 
df_related_topics = pytrend.related_topics()['Netflix']['rising'][:5]


# ## Related Queries
df_related_queries = pytrend.related_queries()['Netflix']['top'][:10]


## Trend
trend_df = pytrend.interest_over_time().reset_index().tail(10)
trend_df = trend_df.rename(columns = {'Netflix':'Interest'})
trend_df



def top_countries():
    fig = go.Figure([go.Bar(x = int_by_reg['Country'], y = int_by_reg['Score'], marker_color = 'indianred'),  #,name = 'Country'
                  ])

    fig.update_layout(title = 'Interest for Netflix across regions',
                      title_x = 0.5,
                  xaxis_title = 'Countries',
                  yaxis_title = 'Relative Interest Score', 
                    barmode = 'group',
                    xaxis=dict(showgrid=False),
              yaxis=dict(showgrid=False) ,
              plot_bgcolor='rgb(255,255,255)'
              )


    return fig 



def top_related_search():
    fig = go.Figure([go.Bar(x = df_related_topics['topic_title'], y = df_related_topics['value'], marker_color = 'indianred'),  #,name = 'Country'
              ])

    fig.update_layout(title = 'Topics related to Netflix',
                  title_x = 0.5,
              xaxis_title = 'Related Topics',
              yaxis_title = 'Score', 
                barmode = 'group',
                xaxis=dict(showgrid=False),
          yaxis=dict(showgrid=False) ,
          plot_bgcolor='rgb(255,255,255)'
          )

    return fig 


def top_related_queries():

    fig = go.Figure([go.Bar(x = df_related_queries['query'], y = df_related_queries['value'], marker_color = 'indianred'),  #,name = 'Country'
              ])

    fig.update_layout(title = 'Queries related for Netflix',
                  title_x = 0.5,
              xaxis_title = 'Related Queries',
              yaxis_title = 'Relative Score', 
                barmode = 'group',
                xaxis=dict(showgrid=False),
          yaxis=dict(showgrid=False) ,
          plot_bgcolor='rgb(255,255,255)'
          )

    return fig 
    

def trend():
    fig = go.Figure([go.Scatter(x = trend_df['date'], y = trend_df['Interest'], marker_color = 'indianred'),  #,name = 'Country'
             ])

    fig.update_layout(title = 'Interest in Netlfix over weeks',
                  title_x = 0.5,
              xaxis_title = 'Dates',
              yaxis_title = 'Interest Score', 
               barmode = 'group',
               xaxis=dict(showgrid=False),
          yaxis=dict(showgrid=False) ,
          plot_bgcolor='rgb(255,255,255)',
          yaxis_range=[0,100]
          )

    return fig


app = dash.Dash(external_stylesheets = [ dbc.themes.FLATLY],)



######### The navigation bar is created using the following code ###################
PLOTLY_LOGO = "https://www.freepnglogos.com/uploads/google-logo-png/google-logo-png-webinar-optimizing-for-success-google-business-webinar-13.png"

navbar = dbc.Navbar(
        [
                dbc.Row(
                    [
                        dbc.Col(html.Img(src = PLOTLY_LOGO, height = "70px"), ),
                        
                        dbc.Col(
              dbc.NavbarBrand("Google Trends 2021 - Netflix", style = {'color':'black', 'fontSize':'25px','fontFamily':'Times New Roman'}
                            ),
              ),

                    ],
                    align="center",
                    className="g-10",
                ),
                
                
                
                
                ]
        )
############################## end of navigation bar ########################



body_app = dbc.Container([
    
     dbc.Row([
         
         # 1st column covering 6 columms for big size screens
         dbc.Col(
              dcc.Graph(id = 'trend', figure = trend()
                        ),
             style = {'height':'450px'},xs = 12, sm = 12, md = 6, lg = 6, xl = 6),
         
         # 2nd column coving 6 columns for big size screens
          dbc.Col(
              dcc.Graph(id = 'regions', figure = top_countries()
                        ),
              style = {'height':'450px'},xs = 12, sm = 12, md = 6, lg = 6, xl = 6
              ),
         
         ]), 
     
     ### Adding the row with 2 columns having one graph component each  
      dbc.Row([
         
          dbc.Col(
              dcc.Graph(id = 'top_related', figure = top_related_search()
                        ),
              style = {'height':'450px'},xs = 12, sm = 12, md = 6, lg = 6, xl = 6
              ),

         
          dbc.Col(
              dcc.Graph(id = 'related_queries', figure = top_related_queries()),style = {'height':'450px'},xs = 12, sm = 12, md = 6, lg = 6, xl = 6
              ),
                  
          ])

    
],fluid = True)


app.layout = html.Div(id = 'parent', children = [navbar, body_app])  ### added navbar to the layout


if __name__ == "__main__":
    app.run_server()

If you want to move from window to window, press Ctrl + w + w.

If you want exit Python in the terminal, press exit().

If you want exit the terminal, press Ctrl + \ and Ctrl n.

About shibatau

I was born and grown up in Kyoto. I studied western philosophy at the University and specialized in analytic philosophy, especially Ludwig Wittgenstein at the postgraduate school. I'm interested in new technology, especially machine learning and have been learning R language for two years and began to learn Python last summer. Listening toParamore, Sia, Amazarashi and MIyuki Nakajima. Favorite movies I've recently seen: "FREEHELD". Favorite actors and actresses: Anthony Hopkins, Denzel Washington, Ellen Page, Meryl Streep, Mia Wasikowska and Robert DeNiro. Favorite books: Fyodor Mikhailovich Dostoyevsky, "The Karamazov Brothers", Shinran, "Lamentations of Divergences". Favorite phrase: Salvation by Faith. Twitter: @shibatau

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.