1. Code
  2. Python

Charting Using Plotly in Python

Scroll to top

Data visualization is a way to understand large chunks of data. Certain trends and patterns might go unnoticed in text format, so data visualization makes it easier to understand what the data is trying to say by visualizing it using different charts.

From the official documentation:

plotly.py is an interactive, browser-based graphing library for Python. Built on top of plotly.js, plotly.py is a high-level, declarative charting library. plotly.js ships with over 30 chart types, including scientific charts, 3D graphs, statistical charts, SVG maps, financial charts, and more.

In this tutorial, you'll be learning about the Plotly data visualization tool. You'll learn how to visualize data in Python using Plotly.

Getting Started

You'll be using a Python framework called Flask to create a Python web application. Once you have the application started, you'll see how to use the Plotly library to visualize data.

Setting Up the Flask Web App 

Flask is a micro-framework for creating web applications using Python. It is quite easy to set up Flask. Install Flask using PIP.

1
pip install flask

Create a directory called PythonPlot. Navigate to the directory and create a file called app.py.

1
mkdir PythonPlot
2
cd PythonPlot

Add the following code to the app.py file.

1
from flask import Flask
2
app = Flask(__name__)
3
4
@app.route("/")
5
def hello():
6
    return "Welcome to TutsPlus!"

Start the web application server using the following code:

1
FLASK_APP=app.py flask run

Point your browser to http://localhost:5000/ and you will have the web application running with the welcome message.

Now let's try to render an HTML page from your Flask web application. 

Create a folder called templates and, inside the templates folder, create a file called index.html. You'll be rendering the graphs created using plotly in the index.html file.

Add the following HTML code to templates/index.html.

1
<!doctype html>
2
<html>
3
4
<head>
5
    <style type="text/css">
6
        .header{
7
            text-align: center;
8
            background-color: rgb(136, 185, 229);
9
            height: 70px;
10
            line-height: 70px;
11
        }
12
        .chart{
13
            margin-top: 30px;
14
            text-align: center;
15
        }
16
    </style>
17
</head>
18
19
<body>
20
21
    <div class="header">
22
        <h2>
23
            Plotly Chart Demo
24
        </h2>
25
    </div>
26
27
    <div id="chart" class="chart">
28
        Chart will be here
29
    </div>
30
31
</body>
32
33
</html>

Import render_template inside the app.py file.

1
from flask import Flask, render_template

Add a new route called showLineChart inside the app.py file. Here is how it looks:

1
@app.route('/showLineChart')
2
def line():
3
    return render_template('index.html')

Save the above changes and restart the server. Point your browser to http://localhost:5000/showLineChart, and you will have the page rendered in your browser.

Plotly Chart Display Plotly Chart Display Plotly Chart Display

Creating a Line Chart Using Plotly

Let's get started with creating a line chart using Plotly. Import the plotly-related libraries in the app.py file.

1
import plotly
2
import plotly.plotly as py
3
import plotly.graph_objs as go

You'll be using NumPy to generate random data for displaying inside the line chart. Import numpy in the app.py file.

1
import numpy as np

You'll be using the numpy.linspace method to create evenly spaced samples calculated over the interval.

1
count = 500
2
xScale = np.linspace(0, 100, count)

The above code creates 500 evenly spaced samples between 0 and 100 for the x-axis scale.

You can use numpy.random.randn to create random samples for the y-axis scale.

1
yScale = np.random.randn(count)

Create a trace using the plotly.graph_objs.scatter method.

1
trace = go.Scatter(
2
    x = xScale,
3
    y = yScale
4
)

You need to convert the trace into JSON format. For that, you'll make use of the plotly JSON encoder plotly.utils.PlotlyJSONEncoder.

1
data = [trace]
2
graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)

Once you have the JSON data, you'll pass it to the template file to be rendered.

1
return render_template('index.html',
2
    graphJSON=graphJSON)

Here is how the app.py file looks:

1
from flask import Flask, render_template
2
import json
3
import plotly
4
import plotly.plotly as py
5
import plotly.graph_objs as go
6
7
import numpy as np
8
9
app = Flask(__name__)
10
11
@app.route('/showLineChart')
12
def line():
13
    count = 500
14
	xScale = np.linspace(0, 100, count)
15
	yScale = np.random.randn(count)
16
17
	# Create a trace

18
	trace = go.Scatter(
19
	    x = xScale,
20
	    y = yScale
21
	)
22
23
	data = [trace]
24
	graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
25
	return render_template('index1.html',
26
	                           graphJSON=graphJSON)

You need to handle the JSON data on the client side to render the chart data. In the templates/index.html file, add references to the following scripts:

1
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
2
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
3
<script src="https://d14fo0winaifog.cloudfront.net/plotly-basic.js"></script>

As seen in the above code, you have referenced the plotly script, as well as jQuery and D3.js, which are also required for plotly to work.

Add the following script to parse the passed-in JSON and render the chart.

1
var graphs = {{graphJSON | safe}};
2
Plotly.plot('chart',graphs,{}); 

The safe filter explicitly marks the string as safe, hence disabling auto-escaping. Once the JSON is parsed into the graph variable, you have passed it to the plotly plot method along with the ID of the div in which to render the line chart.

Here is how the index.html file looks:

1
<!doctype html>
2
<html>
3
4
<head>
5
    <style type="text/css">
6
        .header{
7
            text-align: center;
8
            background-color: rgb(136, 185, 229);
9
            height: 70px;
10
            line-height: 70px;
11
        }
12
        .chart{
13
            margin-top: 30px;
14
            text-align: center;
15
        }
16
    </style>
17
</head>
18
19
<body>
20
21
    <div class="header">
22
        <h2>
23
            Plotly Chart Demo
24
        </h2>
25
    </div>
26
27
    <div id="chart" class="chart">
28
    </div>
29
30
</body>
31
32
    <!-- D3.js -->
33
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
34
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
35
    <!-- Plotly.js -->
36
    <script src="https://d14fo0winaifog.cloudfront.net/plotly-basic.js"></script>
37
38
    <script type="text/javascript">
39
        
40
        var graphs = {{graphJSON | safe}};
41
       
42
        Plotly.plot('chart',graphs,{});        
43
44
    </script>
45
46
</html>

Save the above changes and restart the server. Point your browser to http://localhost:5000/showLineChart, and you will have the line chart rendered.

Line Chart Using PlotlyLine Chart Using PlotlyLine Chart Using Plotly

Creating a Multi-Line Chart Using Plotly

With some modifications to the above line chart, you can convert it into a multi-line chart. To create a multi-line chart, you need to add extra y-axis scales.

Let's start by creating a new route for displaying the multi-line chart.

1
@app.route('/showMultiChart')
2
def multiLine():

Create an x-axis scale, as you did when creating the line chart, and add three y-axis scales.

1
count = 500
2
xScale = np.linspace(0, 100, count)
3
y0_scale = np.random.randn(count)
4
y1_scale = np.random.randn(count)
5
y2_scale = np.random.randn(count)

Create traces using the above xScale and each of the y scales.

1
trace0 = go.Scatter(
2
    x = xScale,
3
    y = y0_scale
4
)
5
trace1 = go.Scatter(
6
    x = xScale,
7
    y = y1_scale
8
)
9
trace2 = go.Scatter(
10
    x = xScale,
11
    y = y2_scale
12
)

Convert the data into JSON using the plotly json encoder, as you did when creating a single line chart.

1
data = [trace0, trace1, trace2]
2
graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
3
return render_template('index.html',
4
                       graphJSON=graphJSON)

Here is what the /showMultiChart routing looks like:

1
@app.route('/showMultiChart')
2
def multiLine():
3
    count = 500
4
    xScale = np.linspace(0, 100, count)
5
    y0_scale = np.random.randn(count)
6
    y1_scale = np.random.randn(count)
7
    y2_scale = np.random.randn(count)
8
9
    # Create traces

10
    trace0 = go.Scatter(
11
        x = xScale,
12
        y = y0_scale
13
    )
14
    trace1 = go.Scatter(
15
        x = xScale,
16
        y = y1_scale
17
    )
18
    trace2 = go.Scatter(
19
        x = xScale,
20
        y = y2_scale
21
    )
22
    data = [trace0, trace1, trace2]
23
    graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
24
    return render_template('index1.html',
25
                           graphJSON=graphJSON)

Save the above changes and restart the server. Point your browser to http://localhost:5000/showMultiChart, and you will have the multi-line chart rendered.

Multi Line Chart Using PlotlyMulti Line Chart Using PlotlyMulti Line Chart Using Plotly

Wrapping It Up

In this tutorial, you learned how to create line and multi-line charts in Python using the Plotly library. You created a Python Flask web app and saw how to create a line chart using sample data generated with the NumPy library.

You can do a lot more using Plotly. For detailed information, I would recommend reading the official documentation.

Source code from this tutorial is available in the tutorial GitHub repo.

How was your experience learning to create charts using Plotly? Do let us know your thoughts and suggestions in the comments below.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.