Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dash Data Visualization and Plotly Integration

Dash Data Visualization and Plotly Integration

In the fields of data science and analytics, data visualization is a crucial step. Through visualization, we can understand data more intuitively and discover patterns and trends within it.

Dash's core visualization functionality relies on Plotly, a powerful open-source data visualization library. Plotly provides rich chart types and highly customizable options, enabling the easy creation of interactive charts.

Dash integrates seamlessly with Plotly through the dcc.Graph component, allowing users to embed Plotly charts directly in Dash applications.

What is Plotly?

Plotly is a JavaScript-based open-source data visualization library that supports multiple programming languages, including Python, R, Julia, and others.

Plotly provides rich chart types such as line charts, bar charts, scatter charts, heatmaps, and more, and supports interactive features such as zoom, pan, and hover tooltips.

Plotly Features:

Core Advantages of Plotly


Dash and Plotly Integration

1. Install Dash and Plotly

Before getting started, we need to install Dash and Plotly. They can be installed with the following command:



pip install dash plotly

或

pip3 install dash plotly

dcc.Graph is the component in Dash used to display Plotly charts. Its core parameter is figure, which specifies the chart's data and layout.

figure parameter:

Example

import

dash

from

dash

import

dcc

,

html

import

plotly.

express

as

px

Create the Dash App

app

=

dash.

Dash

(

name

)

Define the Layout

app.

layout

=

html.

Div

(

[

    dcc.

Graph

(

       

id

=

'example-graph'

,

        figure

=

{

           

'data'

:

[

{

'x'

:

[

1

,

2

,

3

]

,

'y'

:

[

4

,

1

,

2

]

,

'type'

:

'bar'

,

'name'

:

'Data 1'

}

]

,

           

'layout'

:

{

'title'

:

'Sample Chart'

}

       

}

   

)

]

)

Run the application

if

name

==

'main'

:

    app.

run

(

debug

=

True

)

The display effect is as follows:

2. Create a Simple Dash Application

First, we create a simple Dash application that displays a basic Plotly chart.

Example

import

dash

from

dash

import

dcc

,

html

import

plotly.

express

as

px

import

pandas

as

pd

Create a sample dataset

df

=

pd.

DataFrame

(

{

   

"Fruit"

:

[

"Apples"

,

"Oranges"

,

"Bananas"

,

"Apples"

,

"Oranges"

,

"Bananas"

]

,

   

"Amount"

:

[

4

,

1

,

2

,

2

,

4

,

5

]

,

   

"City"

:

[

"SF"

,

"SF"

,

"SF"

,

"NYC"

,

"NYC"

,

"NYC"

]

}

)

Create a Plotly chart

fig

=

px.

bar

(

df

,

x

=

"Fruit"

,

y

=

"Amount"

,

color

=

"City"

,

barmode

=

"group"

)

Initialize the Dash application

app

=

dash.

Dash

(

name

)

Define the application's layout

app.

layout

=

html.

Div

(

children

=

[

    html.

H1

(

children

=

'Hello Dash'

)

,

    html.

Div

(

children

=

'''
        Dash: A web application framework for Python.
    '''

)

,

    dcc.

Graph

(

       

id

=

'example-graph'

,

        figure

=

fig

   

)

]

)

Run the application

if

name

==

'main'

:

    app.

run

(

debug

=

True

)

Code analysis:

The display effect is as follows:

3. Add Interactive Features

The power of Dash lies in its interactive features. Through Dash's callback mechanism, we can dynamically update chart content.

Example

from

dash.

dependencies

import

Input

,

Output

Update the application's layout by adding a dropdown menu

app.

layout

=

html.

Div

(

children

=

[

    html.

H1

(

children

=

'Hello Dash'

)

,

    html.

Div

(

children

=

'''
        Dash: A web application framework for Python.
    '''

)

,

    dcc.

Dropdown

(

       

id

=

'city-dropdown'

,

        options

=

[

           

{

'label'

:

'San Francisco'

,

'value'

:

'SF'

}

,

           

{

'label'

:

'New York City'

,

'value'

:

'NYC'

}

       

]

,

        value

=

'SF'

   

)

,

    dcc.

Graph

(

       

id

=

'example-graph'

,

   

)

]

)

Define the Callback Function

@

app.

callback

(

    Output

(

'example-graph'

,

'figure'

)

,

   

[

Input

(

'city-dropdown'

,

'value'

)

]

)

def

update_graph

(

selected_city

)

:

    filtered_df

=

df

[

df

[

'City'

]

==

selected_city

]

    fig

=

px.

bar

(

filtered_df

,

x

=

"Fruit"

,

y

=

"Amount"

,

color

=

"City"

,

barmode

=

"group"

)

   

return

fig

Run the application

if

name

==

'main'

:

    app.

run

(

debug

=

True

)

Code analysis:

The display effect is as follows:


Plotly Express

Plotly Express is Plotly's high-level interface, capable of creating complex charts with minimal code. It is very suitable for rapid prototyping.

Common Chart Types

1. Line Chart (px.line):

import plotly.express as px

df = px.data.iris()

fig = px.line(df, x='sepal_width', y='sepal_length', title='折线图示例')

2. Bar Chart (px.bar):



fig = px.bar(df, x='species', y='sepal_length', title='柱状图示例')

3. Scatter Chart (px.scatter):



fig = px.scatter(df, x='sepal_width', y='sepal_length', color='species', title='散点图示例')

4. Pie Chart (px.pie):



fig = px.pie(df, names='species', values='sepal_length', title='饼图示例')

5. Heatmap (px.imshow):



import numpy as np

data = np.random.rand(10, 10)

fig = px.imshow(data, title='热力图示例')

The following is a complete Dash application example that creates charts using Plotly Express:

Example

from

dash

import

Dash

,

dcc

,

html

import

plotly.

express

as

px

import

pandas

as

pd

Create sample data

df

=

pd.

DataFrame

(

{

   

'City'

:

[

'Beijing'

,

'Shanghai'

,

'Guangzhou'

,

'Shenzhen'

]

,

   

'Population'

:

[

2171

,

2424

,

1490

,

1303

]

}

)

Create the Dash App

app

=

Dash

(

name

)

Create a bar chart using Plotly Express

fig

=

px.

bar

(

df

,

x

=

'City'

,

y

=

'Population'

,

title

=

'City Population Data'

)

Define the Layout

app.

layout

=

html.

Div

(

[

    dcc.

Graph

(

id

=

'example-graph'

,

figure

=

fig

)

]

)

Run the application

if

name

==

'main'

:

    app.

run

(

debug

=

True

)

The display is as follows:


Using Plotly Graph Objects

Plotly Graph Objects is Plotly's low-level interface, providing finer-grained control, suitable for scenarios requiring high customization.

Common Chart Types

1. Line Chart (go.Scatter):



import plotly.graph_objects as go

fig = go.Figure(data=go.Scatter(x=[1, 2, 3], y=[4, 1, 2], mode='lines'))

2. Bar Chart (go.Bar):



fig = go.Figure(data=go.Bar(x=['A', 'B', 'C'], y=[10, 20, 30]))

3. Scatter Chart (go.Scatter):



fig = go.Figure(data=go.Scatter(x=[1, 2, 3], y=[4, 1, 2], mode='markers'))

4. Pie Chart (go.Pie):



fig = go.Figure(data=go.Pie(labels=['A', 'B', 'C'], values=[10, 20, 30]))

The following is a complete Dash application example that creates charts using Plotly Graph Objects:

Example

from

dash

import

Dash

,

dcc

,

html

import

plotly.

graph_objects

as

go

Create the Dash App

app

=

Dash

(

name

)

Create a bar chart using Plotly Graph Objects

fig

=

go.

Figure

(

data

=

go.

Bar

(

x

=

[

'Beijing'

,

'Shanghai'

,

'Guangzhou'

,

'Shenzhen'

]

,

y

=

[

2171

,

2424

,

1490

,

1303

]

)

)

Set the chart layout

fig.

update_layout

(

title

=

'City Population Data'

,

xaxis_title

=

'City'

,

yaxis_title

=

'Population'

)

Define the Layout

app.

layout

=

html.

Div

(

[

    dcc.

Graph

(

id

=

'example-graph'

,

figure

=

fig

)

]

)

Run the application

if

name

==

'main'

:

    app.

run

(

debug

=

True

)

The display is as follows: