Visualization Python Libraries — Plotly? Part -5

RAVI SHEKHAR TIWARI
DataDrivenInvestor
Published in
9 min readMay 19, 2021

--

In this article will going to see how we can implement different types of graph/charts in python using Plotly Library. If you dont have basic intituition about different types of graphs/charts/plots why they are used how they are used go throught the below mentioned article to have a clear insight before implementing, It is always suggested to build a foundation strong.

For installation and enviroment setup please go through the article mentioned below:

After setting our enviroment and installing packages we can start with our implementation of various graphs using Plotly with python.

  1. Structure of code

Plotly has specific code which is composed of 3 layers has to be written in order to plot the code so here we will discuss the structure of the code which is in specific sequence so it is easier for us to implement in all the section of the article.

1.1. Importing Plotly library

#importing the library import plotly.graph_objects as go # line 1import numpy as np # line 2from plotly.subplots import make_subplots # line 3

The description of the above code is below:

Line 1: This line function is to import the python library —plotly goin our jupyter notebook as go.

Line 2: This line function is to import the python library- numpy in our jupyter notebook as plt.

Line 3: This line function is to import the python library- which will help to sub plot the plotly graph

1.2. Basic ideaPlotting with Plotly

Since, we had imported the library and set our background to black, lets see varoius line of code which is almost same for all graph but with little changes according to the graph we want to plot.

Option 1

fig = go.Figure()fig.add_trace(go.Scatter(x=x, y=x,
mode='lines',
name='linear'))

Option 2

fig = go.Figure()data= go.Scatter(x=x, y=x,
mode='lines',
name='linear')
fig.add_trace(data)

The above code is used to add the different types of the graph to the plotly go object. In plotly there are variety of the graph which we can add. There is another way also of implementing this which is shown above instead of giving the plot directly to the add_trace we assign it to the variable and then the variable is passed as the argument to the add. trace figure.

fig.update_layout(
template='plotly_dark',
title="Line plot",
xaxis_title="X Axis Title",
yaxis_title="Y Axis Title",
legend_title="Linear",

)

The above code is used to format the setting of the appreance of the graph we want to plot. It have variety of arguments but for sake of understanding is have used as per the requirement of the graph i.e. black background title of the graph, x-axis label and y axis label.

1.3. Basic Idea-Sub Plot with Plotly

In above section, we have seen how we can plot graph. In this section we will see how we can how we can plot sub-graph in plotly.

fig = make_subplots(rows=2, cols=1, subplot_titles=("Plot 1", "Plot 2"))  #line 1fig.add_trace(
go.Scatter(x = girls_grades, y =grades_range,
mode='markers',
name="Girls Marks"),
row=1, col=1
) #line 2

fig.add_trace(
go.Scatter(x = boys_grades, y =grades_range,
mode='markers',
name="Boys Marks"),
row=2, col=1
) #line 3



fig.update_layout(
template='plotly_dark',
title="Scatter plot",



) #line 4
fig.show()

The description of the above code is below:

Line 1: This line is used to defined the number of rows, columns and the size of the figure we want to plot.

fig = make_subplots(rows=2, cols=1, subplot_titles=("Plot 1", "Plot 2"))

The above code snippet is very important because this code snippet will structure the plotting so i will explain the code snippet from inside out.

rows=2, cols=1,

This argument will structure the plot into 2 rows and 1 column.

subplot_titles=("Plot 1", "Plot 2")

This argument will structure the plot into 2 rows and 1 column with the above mentioned sub_plot titles.

Line 2 and Line 3: This is used to attach plot the specified rows and column of the sub plot in the graph by specifying the rows=2, cols=1, in the graph.

Line 4: Is used to format the graph lay out discussed in section 1.1.

2. Ploting Different Plotly Graph/Chart

After getting familier with the basic concepts of plotly now our foundation is ready and we can proceed to build the above storey.

2.1. Line Garph

The below snippets demonstrate how we can plot the line graph:

x = np.linspace(0, 6, 100)


fig = go.Figure()


fig.add_trace(go.Scatter(x=x, y=x,
mode='lines',
name='linear'))
fig.add_trace(go.Scatter(x=x, y=x**2,
mode='lines',
name='cubic'))
fig.add_trace(go.Scatter(x=x, y=x*4,
mode='lines', name='polynomial'))
fig.update_layout(
template='plotly_dark',
title="Line plot",
xaxis_title="X Axis Title",
yaxis_title="Y Axis Title",
legend_title="Linet",

)



fig.show()
Fig 1. Line Graph

For description of the line please refer to the Section 2 — i have explained the code snippets.

Line Graph-subplot

The below snippets demonstrate how we can plot the subplot line graph:

fig = make_subplots(rows=2, cols=1, subplot_titles=("Plot 1", "Plot 2",))fig.add_trace(
go.Scatter(x=x, y=x,
mode='lines',
name='linear'),
row=1, col=1
)
fig.add_trace(
go.Scatter(x=x, y=x**2,
mode='lines',
name='cubic'),
row=2, col=1
)
fig.update_layout(
template='plotly_dark',
title="Line plot",
)
fig['layout']['xaxis']['title']='x-axis 1'
fig['layout']['xaxis2']['title']='x-axis 2'
fig['layout']['yaxis']['title']='y-axis 1'
fig['layout']['yaxis2']['title']='y-axis 2'
fig.show()
Fig 2. Sub plot Line Graph

For description of the line please refer to the Section 2 — i have explained the code snippets.

Jupyter Notebook Plotly: Link

Plotly Docs: Link

2.2. Scatterplot

The below snippets demonstrate how we can plot the Scatter Plot graph:

girls_grades = [89, 90, 70, 89, 100, 80, 90, 100, 80, 34]
boys_grades = [30, 29, 49, 48, 100, 48, 38, 45, 20, 30]
grades_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
fig = go.Figure()fig.add_trace(go.Scatter(x=grades_range, y=girls_grades,
mode='markers',
name="Girls Marks"))
fig.add_trace(go.Scatter(x=grades_range, y=boys_grades,
mode='markers',
name="Boys Marks"))
fig.update_layout(
template='plotly_dark',
title="Scatter plot",
xaxis_title='Grades Range',
yaxis_title='Grades Scored',
legend_title='scatter plot',

)
fig.show()
Fig 3 Scatter Plot Graph

For description of the line please refer to the Section 2 — i have explained the code snippets.

Scatterplot Graph-subplot

The below snippets demonstrate how we can plot the subplot Scatter plot graph:

fig = make_subplots(rows=2, cols=1, subplot_titles=("Plot 1", "Plot 2"))fig.add_trace(
go.Scatter(x = girls_grades, y =grades_range,
mode='markers',
name="Girls Marks"),
row=1, col=1
)
fig.add_trace(
go.Scatter(x = boys_grades, y =grades_range,
mode='markers',
name="Boys Marks"),
row=2, col=1
)
fig.update_layout(
template='plotly_dark',
title="Scatter plot",



)
fig['layout']['xaxis']['title']="Girls Grade"
fig['layout']['xaxis2']['title']="Bous Grade"
fig['layout']['yaxis']['title']="Grade RAnge"
fig['layout']['yaxis2']['title']="Grade RAnge"
fig.show()
Fig 4 Sub Scatter Plot Graph

For description of the line please refer to the Section 2 — i have explained the code snippets.

Jupyter Notebook Plotly: Link

Plotly Docs: Link

2.3. Histograms

The below snippets demonstrate how we can plot the Histogram graph:

x = np.random.randn(500)fig = go.Figure(data=[go.Histogram(x=x)])fig.update_layout(
template='plotly_dark',
title="Histogram",
xaxis_title="X Axis Title",
yaxis_title="Y Axis Title",


)
fig.show()
Fig 5. Histogram Graph

For description of the line please refer to the Section 2 — i have explained the code snippets.

Histogram Graph-subplot

The below snippets demonstrate how we can plot the Histogram graph subplot :

x = np.random.randn(500)
y = np.random.randn(500)
fig = make_subplots(rows=2, cols=1, subplot_titles=("Plot 1", "Plot 2"))fig.add_trace(go.Histogram(x=x),row=1, col=1)
fig.add_trace(go.Histogram(x=y),row=2, col=1)
fig.update_layout(
template='plotly_dark',
title="Histogram",
)

fig['layout']['xaxis']['title']='x-axis 1'
fig['layout']['xaxis2']['title']='x-axis 2'
fig['layout']['yaxis']['title']='y-axis 1'
fig['layout']['yaxis2']['title']='y-axis 2'
fig.show()
Fig 6 Histogram Sub plot

For description of the line please refer to the Section 2 — i have explained the code snippets.

Jupyter Notebook Plotly: Link

Plotly Docs: Link

2.4. Bar Charts

The below snippets demonstrate how we can plot the Bar graph:

data = {'A':20, 'B':15, 'C':30,
'D':35, 'E':40}
courses = list(data.keys())
values = list(data.values())

fig = go.Figure([go.Bar(x=courses, y=values)])
fig.update_layout(
template='plotly_dark',
title="Bar Graph",
xaxis_title="Subjects",
yaxis_title="Marks",


)
fig.show()
Fig 7 Bar Graph

For description of the line please refer to the Section 2 — i have explained the code snippets.

Histogram Graph-subplot

The below snippets demonstrate how we can plot the Bar graph subplot :

fig = make_subplots(rows=2, cols=1, subplot_titles=("Plot 1", "Plot 2"))fig.add_trace(go.Bar(x=courses, y=values),row=1, col=1)
fig.add_trace(go.Bar(x=courses, y=values),row=2, col=1)
fig.update_layout(
template='plotly_dark',
title="Bar Graph",
)

fig['layout']['xaxis']['title']="Subjects"
fig['layout']['xaxis2']['title']="Subjects"
fig['layout']['yaxis']['title']="Marks"
fig['layout']['yaxis2']['title']="Marks"
fig.show()
Fig 8 Bar Graph Sub plots

For description of the line please refer to the Section 2 — i have explained the code snippets.

Jupyter Notebook Plotly: Link

Plotly Docs: Link

2.5. Box Plot

The below snippets demonstrate how we can plot the Box Plot:

np.random.seed(10)
data1 = np.random.normal(100, 10, 200)
data2 = np.random.normal(90, 20, 200)
data3 = np.random.normal(80, 30, 200)
data4 = np.random.normal(70, 40, 200)
fig = go.Figure()
fig.add_trace(go.Box(y=data1,name="Plot 1"))
fig.add_trace(go.Box(y=data2,name="Plot 2"))
fig.add_trace(go.Box(y=data3,name="Plot 3"))
fig.add_trace(go.Box(y=data4,name="Plot 4"))
fig.update_traces(boxpoints='all', jitter=0)fig.update_layout(
template='plotly_dark',
title="Box-plot Graph",



)
fig.show()
Fig 9. Box Plot

For description of the line please refer to the Section 2 — i have explained the code snippets.

Jupyter Notebook Plotly: Link

Plotly Docs: Link

Box Plot-subplot

The below snippets demonstrate how we can plot the subplot Box Plot:

fig = make_subplots(rows=1, cols=2)fig.add_trace(go.Box(y=data1,name="Plot 1"), 
row=1, col=1)
fig.add_trace(go.Box(y=data2,name="Plot 1"),
row=1, col=2)
fig.update_traces(boxpoints='all', jitter=0)fig.update_layout(
template='plotly_dark',
title="Box Plot sub Plot",



)
fig.show()
Fig 10 Box Plot Sub plot

For description of the line please refer to the Section 2 — i have explained the code snippets.

2.6. 3d Plot

The below snippets demonstrate how we can plot the 3D-graph:

z = np.linspace(0, 1, 10)
x = 70 * np.sin(35 * z)
y = 55* np.cos(25 * z)
c = x + y
fig = go.Figure(data=[go.Mesh3d(x=x,
y=y,
z=c,
opacity=0.5,
color='rgba(244,22,100,0.6)'
)])
fig.update_layout(
scene = dict(
xaxis = dict(nticks=4, range=[-100,100],),
yaxis = dict(nticks=4, range=[0,10],),
zaxis = dict(nticks=4, range=[0,10],),),

margin=dict(r=20, l=10, b=10, t=10))
fig.show()
Fig 11 3d Plot

For description of the line please refer to the Section 2 — i have explained the code snippets.

Jupyter Notebook Plotly: Link

Plotly Docs: Link

2.7. Heat Maps

A heat map (or heatmap) is a graphical representation of data where values are depicted by color. Heat maps make it easy to visualize complex data and understand it at a glance.

The below snippets demonstrate how we can plot the Heat maps:

import plotly.graph_objects as gofig = go.Figure(data=go.Heatmap(
z=[[1, None, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, -10, 20]],
x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
y=['Morning', 'Afternoon', 'Evening'],
hoverongaps = False))
fig.update_layout(
template='plotly_dark',
title="Heat Map",



)
fig.show()
Fig 12 Heat Maps

For description of the line please refer to the Section 2 — i have explained the code snippets.

Jupyter Notebook Plotly: Link

Plotly Docs: Link

2.8. Pie Chart

The below snippets demonstrate how we can plot the Pie Chart:

langs = ['A', 'B', 'C', 'D', 'E']
students = [23,17,35,29,12]
import plotly.graph_objects as go
fig = go.Figure(data=[go.Pie(labels=langs, values=students)])
fig.update_layout(
template='plotly_dark',
title="pIE Graph",



)
fig.show()
Fig 13Pie Chart

For description of the line please refer to the Section 2 — i have explained the code snippets.

Pie Chart-subplot

The below snippets demonstrate how we can plot the subplot pie chart:

langs = ['A', 'B', 'C', 'D', 'E']
students = [23,17,35,29,12]
fig = make_subplots(rows=1, cols=2, specs=[[{"type": "pie"}, {"type": "pie"}]])fig.add_trace(go.Pie(
values=students,
labels=langs ,
domain=dict(x=[0, 0.5]),
name="Marks"),
row=1, col=1)
fig.add_trace(go.Pie(
values=students,
labels=langs ,
domain=dict(x=[0, 0.5]),
name="Marks"),
row=1, col=2)
fig.update_layout(
template='plotly_dark',
title="pIE Graph",



)
fig.show()
Fig 14 Pie Chart Sub plot

For description of the line please refer to the Section 2 — i have explained the code snippets.

Jupyter Notebook Plotly: Link

Plotly Docs: Link

Conclusion:

In this article, we have seen different types of the graphs/plot implemented using Seaborn to visualise the data. In next article we will discuss implementation with ggplot library in R.

Special Thanks:

As we say “Car is useless if it doesn’t have a good engine” similarly student is useless without proper guidance and motivation. I will like to thank my Guru as well as my Idol “Dr. P. Supraja”- guided me throughout the journey, from the bottom of my heart. As a Guru, she has lighted the best available path for me, motivated me whenever I encountered failure or roadblock- without her support and motivation this was an impossible task for me.

Reference:

Plotly Docs: Link

Matplotlib Docs: Link

Seaborn Docs: Link

Jupyter Notebook Plotly: Link

Jupyter Notebook Seaborn: Link

Jupyter Notebook MatplotliB: Link

Jupyter Notebook installation: Link

Visualization Python Libraries? Part -1: Link

Visualization Python Libraries? Part -2: Link

If you have any query feel free to contact me with any of the -below mentioned options:

YouTube : Link

Website: www.rstiwari.com

Medium: https://tiwari11-rst.medium.com

Github Pages: https://happyman11.github.io/

Google Form: https://forms.gle/mhDYQKQJKtAKP78V7

--

--