Back
Analytics & BI Dashboards

Plotly

Author
Pfactorial
June 19, 2024
Share
Plolty
Data analysis is a crucial skill in today's world, but let's face it, staring at rows and columns of numbers can get tedious. That's where data visualization comes in, transforming dry statistics into captivating stories. And Plotly shines as a powerful tool to weave these narratives.

This blog will be your roadmap for Plotly, guiding you from installation to crafting simple dashboards. So, buckle up and get ready to paint your data with vibrant colours!
Why Plotly?
Plotly offers a range of plot types, for example  line charts, scatter plots, histograms, bar graphs  and so on. So, why opt for Plotly over other visualization tools or libraries? Here's why:

    • Plotly's hover tool capabilities enable the detection of outliers or anomalies in extensive datasets.
    • Its visually appealing design makes it suitable for a broad audience.
    • Plotly allows for limitless customization of graphs, enhancing the meaning and comprehensibility of plots for a diverse audience.

This tutorial aims to provide insight into Plotly, utilising a vast dataset to explain the tool from basic to advanced concepts, covering some popularly used chart types.
Installation
Plotly does not come built-in with Python. To install it type the below command in the terminal.
pip install plotly
Installing plotly
Graphs

In this session, you'll dive deep into some of the most popular Plotly graphs that form the backbone of your dashboards.

Line Graph

A Line Plot in Plotly is a handy tool for showing data trends. With the px.line function, each data point is like a dot on a graph, connected by lines. This helps visualise the ups and downs in two sets of data. The cool thing is, even if you have a lot of data points, this plot can handle it without making you scroll a lot. To create one, just use the line() method from the plotly.express class.

import plotly.express as px
# Creating the Figure instance
fig = px.line(x=[1,2, 3], y=[1, 2, 3])
# printing the figure instance
fig.show()
Output :

Line plotly

Bar Chart

A Bar Graph in Plotly is a simple and effective way to represent data. Using the px.bar function, each data category gets a bar, and you can easily see how they compare. It's great for showing the differences or similarities between different groups of data. Plus, it's straightforward to create one – just use the bar() method from the plotly.express class.

import plotly.express as px  
# using the iris dataset
df = px.data.iris()  
# plotting the bar chart
fig = px.bar(df, x="sepal_width", y="sepal_length")  
# showing the plot
fig.show()
Output

Bar plotly

Pie

A Pie Chart in Plotly is a simple way to represent parts of a whole. With Plotly's px.pie, you can easily create a visual breakdown of data. Each slice in the pie corresponds to a different part of your data. It's a great way to see the proportions of different categories at a glance. To make one, just use the pie() method from the plotly.express class.

import plotly.express as px
# using the tips dataset
df = px.data.gapminder()
# plotting the pie chart
fig = px.pie(df, names="continent")
# showing the plot
fig.show()

Output
pie plotly

Box Plot

A Box Plot in Plotly is a useful way to understand the distribution of data. It shows the minimum, first quartile, median, third quartile, and maximum values in a compact visual. Using px.box, you can create this plot easily. It's great for comparing data between different categories or groups. Just like the Line Plot, it's a helpful tool in Plotly for exploring and interpreting your data.

import plotly.express as px  
# using the tips dataset
df = px.data.tips()  
# plotting the box chart
fig = px.box(df, x="day", y="total_bill")  
# showing the plot
fig.show()
Output

boxplot

Headmap

A Heatmap in Plotly is a useful way to represent data patterns. With the px.imshow function, each data value is like a coloured square on a grid. It's great for visualising how values change across two dimensions. You can easily create a Heatmap using the imshow() method from the plotly.express class

import plotly.express as px
# Load tips dataset from Plotly Express
tip = px.data.tips()
# Calculate correlation matrix for numeric columns
corr_matrix = tip.select_dtypes(['float64', 'int64']).corr()
# Create a heatmap using Plotly Express
fig = px.imshow(corr_matrix, color_continuous_scale='Viridis', labels=dict(color='Correlation'))
# Update layout
fig.update_layout(title='Heatmap of Correlation Matrix for Numeric Columns in the tip dataset')
fig.show()
 Output

Heatmap plot

Scatter plot

A Scatter Plot in Plotly is another useful way to see how two sets of data relate. With px.scatter, each data point is like a dot on the graph. Unlike a line plot, it doesn't connect the dots with lines. It's great for showing individual data points and spotting trends. Just like the Line Plot, it's easy to create a Scatter Plot using the scatter() method from the plotly.express class.

import plotly.express as px
# using the tips dataset
df = px.data.tips()
# plotting the scatter graph
fig = px.scatter(df, x="total_bill", y= ‘tip’, color = ‘sex’)
# showing the plot
fig.show()
Scatter plot

Dashboard
Picture a cool tool that turns your boring data into amazing, interactive stories. That's what Plotly dashboards do! They mix charts, graphs, and maps to make your numbers come alive and keep your audience hooked

In a Plotly dashboard, there are three key components. First, there's the Layout. Think of it as the visual canvas where you arrange your data storytelling elements. It acts as the stage for your charts, maps, and text. You can personalise the layout with colours, fonts, and backgrounds for a cohesive and visually appealing experience.

Next up, we have the Plots; these are the stars of the show, transforming your data into captivating visuals. Plotly offers a vast array of chart types, from classic line graphs and bar charts to scatter plots, pie charts, and heatmaps. Each chart type excels at showcasing specific data relationships and trends.

What sets Plotly apart is its emphasis on Interactivity; it doesn't settle for static visuals. Hover tools reveal hidden details, zoom functionalities let you explore specific sections, and callbacks update charts based on user interactions. This dynamic approach keeps your audience engaged and empowered to delve deeper into your data.

To add depth and clarity to your data story, you can incorporate additional elements like text annotations, images, and even buttons. These elements enhance your dashboard, guiding your audience through your insights.
Plotly dashboard
Layout
Plotly utilises the dash library for creating interactive web applications in Python. The dash library provides a method called app.layout to define the layout of a Dash web application. Here's a brief explanation:
  1.  Dash App Initialization: When creating a Dash app, you typically start by initialising the app: import dash
  2. app = dash.Dash(__name__)

  3. Layout Definition with app.layout: The app.layout method is then used to define the structure and components of the app. It's where you specify the arrangement of elements, such as graphs, charts, text, and interactive components. app.layout = html.Div([
  4.     html.H1('My Dash App'),
        dcc.Graph(id='my-chart'),
        dcc.Dropdown(
            id='my-dropdown',
            options=[
                {'label': 'Option 1', 'value': 'opt1'},
                {'label': 'Option 2', 'value': 'opt2'}
            ],
            value='opt1'
        )]) In this example, html.Div is used to create a division (container) for grouping elements. Inside the division, there's an html.H1 element for a heading, a dcc.Graph component for a chart, and a dcc.Dropdown for an interactive dropdown menu.

  5.  Hierarchy and Nesting: You can create a hierarchical structure by nesting elements within each other. This allows you to organise the layout in a way that makes sense for your application.

  6.  Dynamic Components: The layout can include dynamic components that update based on user interactions. For example, you might have a callback that updates the graph (dcc.Graph) based on the selected value in the dropdown (dcc.Dropdown).
In summary, app.layout is a fundamental part of building Dash applications with Plotly. It allows you to define the structure and appearance of your web app, organising components in a way that makes the application intuitive and user-friendly. The layout is dynamic, and you can use callbacks to update components based on user interactions or changes in the underlying data.

Conclusion
This blog serves as a comprehensive guide to Plotly, a powerful tool for transforming data into impactful visuals. It highlights why Plotly stands out (hover tools, visual design, customization) and delves into popular chart types like line, bar, pie, box, and heatmaps.
DISCOVER MORE. CONNECT WITH US!

Intrigued by what you have read? Dive deeper and stay ahead with the latest insights and trends. We are here to answer your questions and help you explore further.