Sitemap

Plotly: Data Visualization Comprehensive Guide

6 min readJun 26, 2023

--

Data visualization is a crucial aspect of data analysis and communication. It helps us understand patterns, trends, and relationships within our data. Plotly, a powerful Python library, provides an interactive and visually appealing way to create a wide range of data visualizations. In this article, we will explore the key features of Plotly and learn how to leverage its capabilities for effective data visualization. Plotly offers a wide range of chart types and customization options. You can explore the official Plotly documentation (https://plotly.com/python/).

Press enter or click to view image in full size
Photo by Firmbee.com on Unsplash

Plotly is an open-source data visualization library that allows you to create interactive plots and charts in Python, R, and JavaScript. It offers variety of chart types, including line plots, scatter plots, bar charts, histograms, box plots, heatmaps, and more. With Plotly, you can create highly customizable and interactive visualizations that can be embedded in web applications, notebooks, and dashboards.

Installing Plotly

Before we begin, let’s make sure Plotly is installed. You can install it using pip:

pip install plotly

Getting Started with Plotly

As always, import the necessary modules first:

import plotly.express as px
import plotly.graph_objects as go

Plotly Express (px) provides a high-level interface for creating a variety of visualizations with minimal code, while Plotly Graph Objects (go) allows for more advanced customization.

A line plot is useful for visualizing trends over time or continuous variables. The below code will develop an interactive line plot showing the sales trend over the years. If you will hover-over the mouse on the plots, the data points will be displayed. This is created using graph_objects.

We first need to create a figure, on which further plotting can be done.

Then call the add_trace function and call the plot function inside this from graph_objects.

Notice the use of go.Scatter() and assigning mode as ’lines’. At the end, customize the chart with update_layout function and display it with show().

The xaxis property is used to customize the x-axis. tickmode=’linear’ ensures that the tick values are evenly spaced, and dtick=1 sets the interval between tick marks to 1 (one tick per year)

import pandas as pd
import plotly.graph_objects as go

# Create a DataFrame
data = pd.DataFrame({'Year': [2010, 2011, 2012, 2013, 2014],
'Sales': [100, 150, 200, 180, 250]})

# Line plot
fig = go.Figure()
fig.add_trace(go.Scatter(x=data['Year'], y=data['Sales'], mode='lines',
name='Sales'))

# Customize x-axis and y-axis ticks
fig.update_layout(title='Sales Trend',
xaxis=dict(title='Year', tickmode='linear', dtick=1),
yaxis=dict(title='Sales', tickmode='linear', dtick=50))

fig.show()
Press enter or click to view image in full size
Line plot with Graph_Objects

Using ploty.express, you can create the above chart with this code:-

import plotly.express as px
# Line plot
fig = px.line(data, x='Year', y='Sales', title='Sales Trend')
fig.show()

Notice how data is included inside the plotting function with plotly.express

A scatter plot is useful for visualizing the relationship between two numerical variables.

Get Dr. Pooja’s stories in your inbox

Join Medium for free to get updates from this writer.

Notice how by changing the mode (as ‘markers’) in scatter function, the appearance has changed.

# Scatter plot
fig = go.Figure()
fig.add_trace(go.Scatter(x=data['Year'], y=data['Sales'], mode='markers',
name='Sales'))
fig.update_layout(title='Sales vs. Year')
fig.show()
Press enter or click to view image in full size
Scatter Plot without labels, ticks etc

Also without using the ticks, the x-axis appears not so correct with years as 2,010.5!!! Let’s customize it further with color ec and include the years correctly.

fig = go.Figure()
fig.add_trace(go.Scatter(
x=data['Year'],
y=data['Sales'],
mode='markers',
name='Sales',
marker=dict(
color='blue', # Customize marker color
size=10, # Customize marker size
line=dict(
color='black', # Customize marker border color
width=1 # Customize marker border width
)
)
))
fig.update_layout(title='Sales vs. Year',xaxis=dict(title='Year',
tickmode='linear', dtick=1),
yaxis=dict(title='Sales', tickmode='linear', dtick=50))
fig.show()

The marker property is used to customize the appearance of the markers in the scatter plot. The color attribute sets the marker color to blue, the size attribute sets the marker size to 10, and the line property is used to customize the marker border color and width.

Press enter or click to view image in full size
Customized Scatter Plot

# Scatter plot with plotly.express
fig = px.scatter(data, x=’Year’, y=’Sales’, title=’Sales vs. Year’)

A bar chart is useful for comparing categorical variables or aggregating data.

fig = go.Figure()
fig.add_trace(go.Bar(
x=data['Year'],
y=data['Sales'],
name='Sales',
marker=dict(
color=['red', 'green', 'blue', 'yellow', 'orange']
# Customizing the bar colors using marker property
)
))
fig.update_layout(title='Sales by Year')
fig.show()
Press enter or click to view image in full size
Bar chart

Can you add the x-axis and y-axis labels yourself in the above chart? Also try to create this bar plot with px.bar()

A box plot is useful for visualizing the distribution of a numerical variable

fig = go.Figure()
fig.add_trace(go.Box(y=data['Sales'], name='Sales'))
fig.update_layout(title='Sales Distribution')
fig.show()
Press enter or click to view image in full size
Box plot (hovering the mouse displayed the values)
fig = go.Figure()
fig.add_trace(go.Box(
y=data['Sales'],
name='Sales',
boxpoints='all', # to show individual data points alongwith the box
fillcolor='lightblue', # Customizing the box fill color
line=dict(color='darkblue'), # Customizing the box border color
whiskerwidth=0.2, # Customizing the whisker width
marker=dict(
color='red', # Customizing the individual data point color
size=3 # Customizing the individual data point size
)
))
fig.update_layout(title='Sales Distribution')
fig.show()

Execute the above code to get a customized box and compare it with the previous boxplot for yourself!

Also try to create the boxplot with px.box()

Histograms provide insights into the distribution characteristics of a dataset, such as whether it is symmetric, skewed, or multimodal.

fig = go.Figure()
fig.add_trace(go.Histogram(
x=data['Sales'],
nbinsx=10, # Number of bins in the histogram
marker=dict(color='green'), # Customizing histogram color
opacity=0.7 # Adjust histogram opacity
))
fig.update_layout(title='Sales Distribution')
#include the x and y axis labels yourself

fig.show()
Press enter or click to view image in full size
Histogram

# Histogram with plotly.express
fig = px.histogram(data, x=’Sales’, nbins=10, color_discrete_sequence=[‘green’])

A pie chart is a circular statistical graphic that is divided into slices to represent proportions or percentages of a whole. It is a common visualization technique used to display the distribution and relative sizes of different categories within a dataset.

data = pd.DataFrame({'Category': ['Sales', 'Expenses'],
'Amount': [500, 300]})
fig = go.Figure(data=go.Pie(labels=data['Category'], values=data['Amount']))
fig.update_layout(title='Sales vs Expenses')
fig.show()
Press enter or click to view image in full size
Pie Chart
# Pie to donut!
colors = ['rgb(255, 127, 14)', 'rgb(31, 119, 180)']
# Customing the colors for the pie slices

fig = go.Figure(data=go.Pie(
labels=data['Category'],
values=data['Amount'],
marker=dict(colors=colors), # Customizing the colors for pie slices
textinfo='percent+label', # Displaying the percent and label in slices
hole=0.4 # Setting up the size of the central hole
))

fig.update_layout(
title='Sales vs Expenses',
showlegend=False, # Hiding legend as labels are included in slice itself
)

fig.show()
Press enter or click to view image in full size
Pie or Donut!

#pie with plotly.express

fig = px.pie(df, values=’Amount’, names=’Category’)

Plotly is a versatile library that allows you to create a wide range of interactive and visually appealing data visualizations. In this article, we explored the basics of Plotly, including creating line plots, scatter plots, bar charts, box plots, histogram and pie chart.

With Plotly, you can easily create interactive visualizations to explore and communicate your data effectively. Whether you are analyzing trends, comparing variables, or exploring relationships, Plotly provides the tools you need to create engaging and informative plots.

So, go ahead and leverage the power of Plotly to unlock the potential of your data visualization projects!

--

--

Dr. Pooja
Dr. Pooja

Written by Dr. Pooja⁠

Academician, Mentor, Researcher - Artificial Intelligence | Data Science | Machine Learning | Data Analytics