A Simple Visualization with Plotly

In this blog post, we will discuss how to create a simple visualisation with python library - plotly. Plotly is an open source library of python. It is widely used in data visualisations and offers a variety of visualisations. Knowledge of python is a prerequisite for this.

Let us create a simple column chart based on below fictitious sales data:

MonthProductItems SoldItem PriceSales Amount
Jan 22Product A5110510
Feb 22Product A7110710
Mar 22Product A7210720
Jan 22Product B95201900
Feb 22Product B76201520
Mar 22Product B60201200
Jan 22Product C1630480
Feb 22Product C41301230
Mar 22Product C34301020

We will use Google Colab  for this activity. 

Create a new notebook with Google Colab.

From the left sidebar, click on files and then upload this csv to the session




Then we will import the necessary python packages - pandas and plotly express.

import pandas as pd
import plotly.express as px
 
We have this data in a csv file.  We will load this data into a data frame with read_csv function of pandas. Pandas can read the data from variety of sources like csv, parquet, csv, xml, json and from relational databases with SQL as well. More on it in some other blog post. Let us load this data into a pandas data frame with below line:

df = pd.read_csv('sample_sales_data.csv')

Then let us verify the data read in pandas data frame with "head" method of data frame.
df.head()
This method prints the first five rows of data frame by default. 

Let us now create bar chart with below code.

fig = px.bar(data_frame=df, x='Month', y='Sales Amount', color='Product',
title='Sales Amount by Months and Product', width=700, height=500)
fig.show()


Here, are the details of parameters passed to the px.bar function. 
data_frame : The data frame used as a source to plot the bars
x : The column name in the data frame which should be plotted on the x axis. In this case it is the month.
y : The column name in the data frame which should be plotted on the y axis. In this case, it is the measure - Sales Amount.
color : the column name in the data frame which represents the legends field. The bars are stacked by default and colored as according to this column. 
title : Title of the chart which appears on the top
width : Width of the chart in pixels
height : Height of the chart in pixels

When you hover over the bar, it shows you tool tips indicating product, month and sales amount. The chart can be zoomed in / out, saved as an image with the bar shown just above the chart. 



This is a simple bar chart with plotly. It can be customised in variety of ways including showing values on the bars or use custom color pallet. More on these customisation in some other blog post.

Thank you!  

Comments

Popular posts from this blog

A Dash App With Visualization Interacting with AG Grid

Cross-filtering Visualizations with Dash Plotly