Building Interactive Visualisations Using Plotly

Plotly is a powerful data visualization library that allows you to create interactive charts and graphs. With Plotly, you can create everything from simple line charts to complex 3D visualisations with ease. In this article, we’ll cover the basics of creating interactive visualizations using Plotly, and we’ll provide examples to help you get started.


Getting Started with Plotly

Before we dive into creating visualizations with Plotly, we need to install it. You can install Plotly using pip, which is a Python package manager. Open up a terminal or command prompt and type the following command:

pip install plotly

Once Plotly is installed, you can start creating visualizations. In this article, we’ll use Jupyter Notebook, which is an interactive coding environment that allows you to write and run Python code in a web browser.

To get started, open up Jupyter Notebook and create a new notebook. Import the necessary libraries by typing the following code:

import plotly.graph_objects as go
import plotly.express as px
import numpy as np

This imports the Plotly library and NumPy, which is a library for working with arrays and matrices in Python.


Creating a Simple Line Chart

Let’s start with a simple line chart. First, we need some data to plot. For this example, we’ll use the following data:

x = np.arange(0, 10, 0.1)
y = np.sin(x)

This creates an array of x-values ranging from 0 to 10 with a step of 0.1, and an array of y-values that are the sine of each x-value.

Now, let’s create a line chart using Plotly:

fig = go.Figure(data=go.Scatter(x=x, y=y))
fig.show()

This creates a new Figure object and adds a scatter plot to it using the x and y data. Finally, we call the show() method to display the chart in the Jupyter Notebook.

If you run this code, you should see a simple line chart with the sine wave as shown below:

Plotly - Line Chart Simple

Customising the Line Chart

Let’s say we want to customize the line chart. We can change the color of the line, add a title, and label the x and y axes.

fig = go.Figure(data=go.Scatter(x=x, y=y, line=dict(color='red')))
fig.update_layout(title='Sine Wave', xaxis_title='X', yaxis_title='Y')
fig.show()

This code creates a new Figure object and sets the color of the line to red. It also updates the layout of the chart to include a title, and labels for the x and y axes.

Plotly - Line Chart Colored

Adding Multiple Lines to the Chart

What if we want to add multiple lines to the chart? We can do that by adding multiple Scatter traces to the Figure object.

y2 = np.cos(x)

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=y, name='Sine'))
fig.add_trace(go.Scatter(x=x, y=y2, name='Cosine'))
fig.update_layout(title='Sine and Cosine Waves', xaxis_title='X', yaxis_title='Y')
fig.show()

This code creates a new Figure object and adds two Scatter traces to it, one for the sine wave and one for the cosine wave. It also updates the layout of the chart to include a title and labels for the x and y axes.

Plotly - Line Chart

Scatter Plot

A scatter plot is a chart that displays data points as markers on a two-dimensional coordinate system. We’ll create a scatter plot of the tips dataset to visualize the relationship between the total bill amount and tip amount.

df = px.data.tips()

fig = px.scatter(df, x="total_bill", y="tip", title="Tips vs Total Bill Amount")
fig.show()

In this code snippet, we first load the tips dataset using the px.data.tips() function. We then use the px.scatter() function to create a scatter plot with the total bill amount on the x-axis, tip amount on the y-axis, and a title for the chart. The fig.show() function displays the visualisation.

Plotly - Scatter Plot

Time Series Chart

A line chart is a chart that displays data as a series of points connected by lines. We’ll create a line chart of the stock prices of Apple Inc. to visualise the trend in stock prices over time.

import pandas as pd

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")

fig = px.line(df, x="Date", y="AAPL.Close", title="Apple Inc. Stock Prices")
fig.show()

In this code snippet, we load the stock prices of Apple Inc. from a CSV file using the pd.read_csv() function. We then use the px.line() function to create a line chart with the date on the x-axis and the closing price of the stock on the y-axis. The fig.show() function displays the visualisation.

Plotly - Time Series Chart

3D Scatter Plot

In this explanation, we’ll create a 3D scatter plot using Plotly.

In this example, we have created a DataFrame with four columns: x, y, z, and color. The x, y, and z columns contain the coordinates of the points that we want to plot in 3D space. The color column contains the color of each point.

import plotly.graph_objs as go
import pandas as pd

df = pd.DataFrame({'x': [1, 2, 3, 4, 5],
                   'y': [5, 4, 3, 2, 1],
                   'z': [1, 2, 3, 4, 5],
                   'color': ['red', 'green', 'blue', 'yellow', 'orange']})

fig = go.Figure(data=[go.Scatter3d(
    x=df['x'],
    y=df['y'],
    z=df['z'],
    mode='markers',
    marker=dict(
        color=df['color'],
        size=10,
        opacity=0.8
    )
)])

fig.show()

Now, let’s create a 3D scatter plot using the data we just created:

Plotly 3D Scatter Plot

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top