Unleash the Power of 3D Visualization with Plotly’s Graph Objects

Plotly's Graph

In the realm of data visualization, Plotly stands as a shining beacon, and at its core lies the graph objects module. This article delves deep into the world of Plotly’s graph objects, explaining their functionality from the ground up. We’ll explore the most commonly used charts and unveil the reasons why using graph objects over Plotly Express can be a game-changer for your data visualization endeavors.

Why Choose Graph Objects Over Plotly Express?

Plotly’s library is known for its prowess in creating interactive and exquisite plots, but when it comes to certain 3D trace-types like mesh or isosurface, Plotly Express falls short. This is where the graph objects module comes into play. Here’s why you should consider it:

1. Unleash the Power of 3D Visualization

With graph objects, you can dive into the world of 3D visualization without limitations. Unlike Plotly Express, which struggles with 3D trace-types, the graph objects module empowers you to create stunning 3D plots that elevate your data storytelling.

2. Keep Your Data Secure

When using Plotly Express, your data is uploaded to external servers for graphical representation. In contrast, graph objects ensure your data stays on your local machine, safeguarding it against potential security concerns.

3. Comprehensive Data Science Toolkit

If you’re on the lookout for a complete repository of Python libraries for data science, look no further. Graph objects offer a versatile toolkit that complements your data science arsenal, enabling you to tackle diverse visualization challenges with ease.

A Closer Look at the Data

Before we dive into the practical aspects, let’s acquaint ourselves with the dataset we’ll be working with. The data at hand revolves around the end-of-day Nifty 50 stock prices, featuring 13 essential features related to these stocks. This dataset has been sourced from Kaggle, and here’s a breakdown of the features:

  • Symbol: The stock’s name.
  • Open: The opening price when the market commenced trading.
  • High: The highest recorded price within the day.
  • Low: The lowest recorded price within the day.
  • LTP: Last Traded Price – the price at which the last transaction occurred.
  • Chng: The amount of change in the stock price.
  • % Chng: The percentage change in the stock price.
  • Volume: The total trading volume for the day.
  • Turnover: The total turnover of the company.
  • 52w H: The highest price the stock has traded at over the past 52 weeks.
  • 52w L: The lowest price the stock has traded at over the past 52 weeks.
  • 365d % Chng: The percentage change in the stock’s price over the past 365 days (1 year).
  • 30d % Chng: The percentage change in the stock’s price over the past 30 days (1 month).

Visualization with Plotly Graph Objects

Importing Libraries

Let’s begin our data visualization journey by importing the necessary libraries:

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

Reading and Preprocessing the Dataset

Next, we need to read and preprocess the dataset. This involves removing commas from certain values and converting all relevant values to float for seamless data visualization.

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()

Bar Plot

Now, let’s create a bar plot to visualize the total volume of stock trading. We’ll follow these steps:

Step 1: Define a blank figure using the go.Figure() class and store it in a variable called “fig.”

fig = go.Figure()

Step 2: Add a trace to the blank figure using the add_trace() class. Inside the trace, specify the plot details, including the x-axis, y-axis, plot name, and other parameters.

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

Step 3: Display the plot by calling the variable in which the figure was stored and using the show() function.

fig.show()

Enhancing the Bar Plot

The initial plot lacks some essential elements like a grid format background, x-axis label, y-axis label, and a title. Let’s enhance the plot by updating its layout using the update_layout() class.

Step 4: Use the update_layout() class to update various aspects of the plot, including legend visibility, plot background color, font settings, axis labels, and the title.

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'), )

With these updates, our final code for the bar plot looks 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()

With these updates, our bar plot is now visually appealing, sorted in descending order, and includes essential elements like axis labels and a title.

Scatter Plot

Now, let’s explore scatter plots to visualize the variation between the highest and lowest stock prices 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()

This scatter plot provides a clear picture of how stock prices vary between their highest and lowest points at the end of the day. It includes markers and lines for enhanced data representation.

Pie Chart

Now, let’s create a pie chart to visualize the percentage of annual change in stock prices.

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()

This pie chart provides a visual representation of how stock prices have changed over the course of a year, making it easy to identify trends and outliers.

Subplots

Lastly, let’s create subplots to display both the scatter plot of annual high and low stock prices and the bar plot of the percentage of annual change in stock prices. This allows us to compare these two aspects in a single view.

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 variation 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()

With these subplots, we can simultaneously visualize the annual high and low stock prices alongside the percentage of annual changes, offering a comprehensive view of stock performance.

Final Verdict

In conclusion, the graph objects module forms the backbone of every graph produced by Plotly. In this article, we’ve not only explored when to use graph objects but also delved into their implementation, enabling you to create interactive and captivating visuals from your data.