Plotly is an open-sourced Python library used for visualizing data by creating interactive and exquisite plots. Graph objects are pictorial representations of systems of objects interconnected by links. The plotly.graph_objects module contains a hierarchy of Python classes that represent non-leaf nodes in this figure schema. “Graph objects” are instances of these classes. In this article, we will look at how to use graph objects (module) of the Plotly library, explaining it from the ground up, and covering all of the most commonly used charts. The following are the points and plots that this article will cover.

Table of contents

  1. Why use graphic objects over Plotly express?
  2. Description of data
  3. Visualization with Plotly graph objects
    • Bar plot
    • Scatter plot
    • Subplots

Let’s start with the advantages of graphic objects over Plotly express.

Why use graphic objects over Plotly express?

Plotly’s library uses graph objects in the background to produce its figures unless manual construction is done from dictionaries. Plotly express has many advantages but the question is why to use the graphic object module. Let’s see why:

  • Figures that use certain 3D trace-types, such as mesh or isosurface, are not yet possible with Plotly Express.  
  • Plotly express uploads the data on its server to return the graphical representation whereas in graph object there is no such thing happening.

Description of data

The data used in this article is about the end of the day nifty 50 stock prices with a total of 13 features related to the stocks. This data has been taken from the kaggle repository which is mentioned in the references. The description of the features is listed below.

  • Symbol: Name the stock 
  • Open: The opening price of the particular stock when the market opened
  • High: The highest price of the stock within the day 
  • Low: Lowest price of the stock within the day
  • LTP: Last Traded Price stands for the price of a stock on which the last transaction or trade occurred.
  • Chng: Amount of change in the  stock price
  • % Chng: Percentage of change
  • Volume: Total amount of stock trading for the day
  • Turnover: Total turnover of the company
  • 52w H: the highest price that the security/ stock has traded over 52 weeks i.e. a year
  • 52w L: the lowest price that the security/ stock has traded over 52 weeks i.e. a year
  • 365 d % chng: percentage of change on the stock in 365 days (year)
  • 30 d % chng: percentage of change on the stock in 30 days (month)

Sample

Visualization with Plotly graph objects

Visualize the data with the graphic object module of plotly and learn how to use different classes of this module.

Importing libraries: 

import pandas as pd
import numpy as np
import plotly.graph_objects as go 

Reading dataset and preprocessing:

df=pd.read_csv('Nifty50.csv')
df[['52w H','52w L','Open', 'High', 'Low']]=df[['52w H','52w L','Open', 'High', 'Low']].replace(",","",regex=True)
df[['LTP','Turnover (crs.)']]=df[['LTP','Turnover (crs.)']].replace(",","",regex=True)
df[['52w H', '52w L','Open', 'High', 'Low', 'LTP','Turnover (crs.)']]=df[['52w H', '52w L','Open', 'High', 'Low', 'LTP','Turnover (crs.)']].astype(float)
df.head()

Dataset needed some preprocessing there were commas (,) in the values so needed to replace those as well convert all the values to float for using them in the data visualization.

Before preprocessing:

After preprocessing:

Bar plot

fig=go.Figure()
fig.add_trace(go.Bar(x=df['Symbol'], 
                       y=df['Volume (lacs)'],
                       name ='Total volume',
                       visible=True
                     ))
fig.show()

Step 1: Defining the blank figure using go.Figure() class and the figure stored in a variable name “fig”.

Step 2: Now need to add a plot to the blank figure stored in the variable, for which the add_trace() class is used. Inside the trace, the class adds the plot which is to be plotted. So, this bar plot is given as an input, then defining the x-axis, y-axis, name of the plot and other parameters.

Step 3: Now call the variable in which the figure was stored and display the plot by using the show() function.

Now the graph is plotted but it does not look like this has a grid format background, no x-axis label or y-axis label, no title. So, for adding all this content to the graph we need to update the layout of the plot.

Step 4: Use the update_layout() class to update any parameter of the graph.

fig.update_layout(showlegend=False, 
                    plot_bgcolor='rgba(0,0,0,0)',
                    font=dict(family='Arial', 
                              size=12, 
                              color='black'),
                  xaxis = dict(showgrid=False,tickangle = -45,categoryorder='total descending',title_text='Name of stocks'),
                  yaxis = dict(title_text='Total amount of stocks traded'),
                  title=dict(text = 'Total volume of stock EOD',
                             font=dict(family='Arial', 
                                       size=18, 
                                       color='black'),
                             x=0.5,
                             y=0.9,
                             xanchor='center',
                             yanchor='top'),
                  )

In the above code, the background colour is changed to white, font is set for the text shown in the graph, x-axis and y-axis are described with their properties like the angle at which the labels should be presented and name of axis, and at last, the title of the plot is added with some properties of like font and positioning. So, the final code will look like this:

fig=go.Figure()
fig.add_trace(go.Bar(x=df['Symbol'], 
                       y=df['Volume (lacs)'],
                       name ='Total volume',
                       visible=True
                     ))
 
fig.update_layout(showlegend=False, 
                    plot_bgcolor='rgba(0,0,0,0)',
                    font=dict(family='Arial', 
                              size=12, 
                              color='black'),
                  xaxis = dict(showgrid=False,tickangle = -45,categoryorder='total descending',title_text='Name of stocks'),
                  yaxis = dict(title_text='Total amount of stocks traded'),
                  title=dict(text = 'Total volume of stock EOD',
                             font=dict(family='Arial', 
                                       size=18, 
                                       color='black'),
                             x=0.5,
                             y=0.9,
                             xanchor='center',
                             yanchor='top'),
                  )
fig.show()

Now the plot is sorted in descending order, it has x labels & y labels and a title is added to the plot. As we have seen the plotting of bar plots similarly let’s see the plotting of other basic plots.

Scatter plot

Plotting a scatter plot with lines connecting those data points to see the variation of the highest and lowest price of the stocks at the end of the day.

fig=go.Figure()
fig.add_trace(go.Scatter(x=df['Symbol'], y=df['52w H'],
                    mode='lines+markers',
                    name='high'))
fig.add_trace(go.Scatter(x=df['Symbol'], y=df['52w L'],
                    mode='lines+markers',
                    name='low'))
fig.update_layout(showlegend=True, 
                    plot_bgcolor='rgba(0,0,0,0)',
                    font=dict(family='Arial', 
                              size=12, 
                              color='black'),
                  xaxis = dict(showgrid=False,tickangle = -45,title_text='Name of stocks'),
                  yaxis = dict(title_text='Price of stocks'),
                  title=dict(text = 'Variation between highest and lowest stock price',
                             font=dict(family='Arial', 
                                       size=18, 
                                       color='black'),
                             x=0.5,
                             y=0.9,
                             xanchor='center',
                             yanchor='top'),
                  )
fig.show()

Pie chart

Let’s see the percentage of annual change in the stock price with the help of a pie chart.

fig=go.Figure()
fig.add_trace(go.Pie(labels=df['Symbol'], values=df['365 d % chng'], name="Change in year"))
fig.update_traces(textposition='inside')
fig.update_layout(uniformtext_minsize=12, 
                  uniformtext_mode='hide',
                  title=dict(text = 'Percentage of annual change in stock price',
                             font=dict(family='Arial', 
                                       size=18, 
                                       color='black'),
                             x=0.5,
                             y=0.9,
                             xanchor='center',
                             yanchor='top'))              
fig.show()

Subplots

Now let’s plot the above scatter plot and a bar plot of the percentage of annual change in the stock with respect to the annual high and low of stock prices. To plot this kind of chart, you need to create a subplot with two rows and one column. Let’s see how to display multiple plots in one plot with the help of subplots.

import plotly.subplots as splt
fig_sub = splt.make_subplots(rows=2, cols=1,
                      row_heights=[0.7,0.9],
                      subplot_titles=("Annual High and Low for stocks", 
                                      "Percentage of annual change in stocks"))
fig_sub.add_trace(go.Scatter(x=df['Symbol'], y=df['52w H'],
                    mode='lines+markers',
                    name='high'),
                    row=1, col=1)
fig_sub.add_trace(go.Scatter(x=df['Symbol'], y=df['52w L'],
                    mode='lines+markers',
                    name='low'),row=1, col=1)
fig_sub.add_trace(go.Bar(x=df['Symbol'], 
                       y=df['365 d % chng'],
                       name ='% change/annum',
                       visible=True),row=2, col=1
                     )
fig_sub.update_xaxes(tickangle = -45, row=1, col=1)
fig_sub.update_xaxes(tickangle = -45, row=2, col=1)
fig_sub.update_layout(showlegend=True, 
                    plot_bgcolor='rgba(0,0,0,0)',
                    font=dict(family='Arial', 
                              size=12, 
                              color='black'),
                      title=dict(text = 'Annual varation in stocks',
                             font=dict(family='Arial', 
                                       size=18, 
                                       color='red'),
                             x=0.5,
                             y=0.9,
                             xanchor='center',
                             yanchor='top'),
                      height=550               
                  )
fig_sub.show()

fig_sub.show()

The subplot with two rows and one column by using the make_subplot() class of subplots module and store it in a variable(‘fig_sub’). The variable in which it is stored ‘fig_sub’ is used for updating and adding traces same as explained earlier.

Final verdict

The graph object module is the backbone of every graph produced by Plotly. In this article, we have learned about when to use graph objects and we also went through their implementation to create interactive and interesting visuals with the help of data.

References