Use-case:
A Python tutorial for data visualization beginners guide on how to create interactive chart in Python. In this blog, we use a bar chart as an example and create the step by step guide on creating an interactive bar chart using plotly or plotly.px package in Python. We also started with some typically needed data cleaning steps in the path to preparing the visualization.
The two features we added to the interactive chart are:
- customizing chart title, x axis, and y axis labels and documentation on other options available in plotly
- Change color of bar chart based on a variable or features (a dataframe column) and allow interactive control based on color
Video Tutorial for this blog is available here:
Check out these related tutorial in your convenient time:
- For python related tutorials, see this playlist of video tutorials: https://www.youtube.com/playlist?list=PL_b86y-oyLzAQOf0W7MbCXYxEkv27gPN6
- For Data Viz related tutorials see this playlist of video tutorials: https://www.youtube.com/playlist?list=PL_b86y-oyLzAHJan5avUJ8l2X72sMGpxX
Step1: package
# required packages and initial settings for reading a google sheet data from python in google colab
from google.colab import auth
auth.authenticate_user()
import gspread
from google.auth import default
creds, _ = default()
gc = gspread.authorize(creds)
# other required packages depending on the need
import pandas as pd
import plotly.express as px
Step2: data input
We use a mock data on online traffic counts for a website in different dates through different channels. Here, we want to simply visualize the frequency of organic traffic on the website over time.
Step3: Purpose of chart and data cleaning needed for that
We need to make sure the date variable is datetime type feature and the organic or other numerical variable are actually some sort of integer or numeric type feature in pandas / python.
Step4: a simple interactive bar chart with plotly.px
using the px.bar function in here:
fig = px.bar(data, x='Date', y='organic')
fig.show()
fig = px.bar(data, x='Date', y='organic',
labels={'organic':'Traffic counts'},
title="Traffic numbers from organic mediums")
fig.show()
Step4: a change color based on column value in pandas & plotly.px
fig = px.bar(data, x='Date', y='organic',
labels={'organic':'Traffic counts'},
title="Traffic numbers from organic mediums with different events",
color='event')
fig.update_layout(xaxis={'categoryorder':'category ascending'})
fig.show()
Related Links
- code solution script: https://colab.research.google.com/drive/17EcIYG3KFfwDg752-4RP4h4iwABrfXdh?usp=sharing
- plotly bar chart documentation: https://plotly.com/python/bar-charts/
- Bar chart plotly all options for customization: https://plotly.com/python/bar-charts/