Try   HackMD
tags: python plotly.express.scatter() plotly.io.write_html()

Data visualisation in Python

Chang’s working examples created in Python


Colours

Pick a RGB color code from rgb color picker

RGB Colour picker


Packages

dash

How does the app.callback decorator work? Understanding the app.callback decorator

# Step 2: adjust the app layout adding two components- a graph and a dropdwon
## Note that the code for creating figures is in the update_figure function
app.layout = html.Div([
    dcc.Graph(id='graph'),
    dcc.Dropdown(   id='year-picker', # id is used to connect to callback
                    options=year_options, # year_options is defined above the app.layout call
                    value=df['year'].min() # set default value to minimum year
                )
])

# This callback specifies the source of input, grabbing values from component_id='year-picker' and output the values to component_id='graph'. Inside @app.callback, Output and Input are abbreviated forms of dash.dependencies.Output and dash.dependencies.Input. Note how we imported them from dash.dependencies by name.
@app.callback(
    # Connect the Output to the dcc.Graph component using dash.dependencies.Output
    Output( component_id='graph',
            component_property='figure'),
    # Connect the user input to the dcc.Dropdown using dash.dependencies.Input
    [Input( component_id='year-picker',
            component_property='value')]
            )
# Step 3: create a function to connect to the dcc.Dropdown() component (via the app.callback decorator?)
def update_figure(selected_year):
    # Filter data using selected year from the dropdown menu
    filtered_df = df[df['year'] == selected_year]
    # Create a trace for each continent
    traces = []
    for continent_name in filtered_df['continent'].unique():
        # Filter data again by continent, creating a trace for each of the continents
        df_by_continent = filtered_df[filtered_df['continent'] == continent_name]
        traces.append(go.Scatter(
            x=df_by_continent['gdpPercap'],
            y=df_by_continent['lifeExp'],
            text=df_by_continent['country'],
            mode='markers',
            opacity=0.7,
            marker={'size': 15},
            name=continent_name
        ))
    # Return a dictionary that will be passed to the dcc.Graph call
    return {
        'data': traces,
        'layout': go.Layout(
            title='My plot',
            xaxis=dict(type='log', title='GDP Per Capita'),
            #xaxis={'type': 'log', 'title': 'GDP Per Capita'},
            yaxis=dict(title='Life Expectancy'),
            #yaxis={'title': 'Life Expectancy'},
            hovermode='closest'
        )
    }

Notice that selected_year is linked to component_property='value' of the input of the callback(). What the callback does here is when value of the dcc.Dropdown changes, the callback() will use the update_figure() function to update the property component_property='figure' of the graph component_id='graph' In other words, the @app.callback() simply pass the input from the dcc.Dropdown component to the update_figure() function and pass the output of the update_figure() function to the dcc.Graph component.


plotly-orca

conda install -c plotly plotly-orca psutil requests install this package via conda. pip.exe is not working Static Image Export in Python Why plotly-orca is unable to install via pip

conda install -c plotly plotly-orca psutil requests


Plot types

Box plot

Create one box plot[1], visualising 3 continuous variables that are not normally distributed- Heart rate, respiratory rate, and system providing oxygen saturation (SpO2)

plot file path: D:\googleDrive\Job\UQ_509098_Data-analyst_Paediatric-Critical-Care-Research-Group\Practical-Assessment\boxplot_HeartRate-RespiratoryRate-spo2_full-sample.png

boxplot


Create one box plot with 2 facet columns[2], visualising the 3 continuous variables that are not normally distributed Heart rate, respiratory rate, and system providing oxygen saturation (SpO2) in different study hospitals

plot file path: D:\googleDrive\Job\UQ_509098_Data-analyst_Paediatric-Critical-Care-Research-Group\Practical-Assessment\boxplot_HeartRate-RespiratoryRate-spo2_in-3-study-sites.png

boxplot-facet_col


Save plots

Save 1 plotly plot as a html

How To Create a Plotly Visualization And Embed It On Websites

import plotly.express as px
# Create a scatter plot by plotly
fig = px.scatter(df, x='Neighborhood', y='Price (US Dollars)'
                 ,size='Accommodates'
                 , hover_data=['Bedrooms', 'Wifi', 'Cable TV', 'Kitchen', 'Washer', 'Number of Reviews']
                 ,color= 'Room Type')
fig.update_layout(template='plotly_white')
fig.update_layout(title='How much should you charge in a Berlin neighborhood?')
fig.show()

# To generate the HTML file for the plotly visualization, use:
import plotly.io as pio
pio.write_html(fig, file=’index.html’, auto_open=True)

Save multiple plotly plots as a html

Plotly saving multiple plots into a single html (python)

import plotly.express as px
# Make plot 1
# Box plots for full sample
fig1= px.box(data3, title="Box plot of heart rate, respiratory rate and SpO2", x="variable", y="value",notched=True, points="all",color="Study Hospital", template='presentation') 
# Tweaking the default setting in plotly objects
fig1.update_xaxes(tickangle=0, tickfont=dict(family='Rockwell', color='crimson', size=15))

# Make plot 2
# Box plots in study groups
fig2= px.box(data3, title="Box plot of heart rate, respiratory rate and SpO2", x="variable", y="value",notched=True, points="all",color="Study Hospital", facet_col='Study Group', template='presentation') # , template='presentation'
# Tweaking the default setting in plotly objects
fig2.update_xaxes(tickangle=0, tickfont=dict(family='Rockwell', color='crimson', size=15))

# Save the 2 plotly plots as a HTML file
## full_html=False which will give you just DIV containing figure. You can just write multiple figures to one HTML by appending DIVs containing figures
output_file_path= "D:/googleDrive/Job/UQ_509098_Data-analyst_Paediatric-Critical-Care-Research-Group/Practical-Assessment/boxplots.html"
with open(output_file_path, 'a') as f:
    f.write(fig1.to_html(full_html=False, include_plotlyjs='cdn'))
    f.write(fig2.to_html(full_html=False, include_plotlyjs='cdn'))

  1. Python script file path: D:\googleDrive\Job\UQ_509098_Data-analyst_Paediatric-Critical-Care-Research-Group\Practical-Assessment\Chang_PCCRG_dashboard_visualise-HeartRate-RespiratoryRate-spo2.ipynb ↩︎

  2. Python script file path: D:\googleDrive\Job\UQ_509098_Data-analyst_Paediatric-Critical-Care-Research-Group\Practical-Assessment\Chang_PCCRG_dashboard_visualise-HeartRate-RespiratoryRate-spo2.ipynb ↩︎