Beginner's Python
Line graphs, scatter plots, and bar graphs Multiple plots
(cont.) You can include as many data series as you want in a
visualization. To do this, create one dictionary for each
Making a bar graph
Cheat Sheet - Plotly To make a bar graph, pass your data to the Bar() graph object.
from plotly.graph_objs import Bar
data series, and put these dictionaries in the data list. Each
of these dictionaries is referred to as a trace in the Plotly
documentation.
--snip--
Plotting squares and cubes
What is Plotly? Here we use the 'name' attribute to set the label for each trace.
data = [Bar(x=x_values, y=squares)]
Data visualization involves exploring data through from plotly.graph_objs import Scatter
visual representations. Plotly helps you make visually # Pass the data and a filename to plot(). from plotly import offline
appealing representations of the data you’re working [Link](data, filename='[Link]')
with. Plotly is particularly well suited for visualizations x_values = list(range(11))
that will be presented online, because it supports Adding a title and labels squares = [x**2 for x in x_values]
interactive elements. cubes = [x**3 for x in x_values]
Using layout objects
The Layout class allows you to specify titles, labels, and other data = [
Installing Plotly formatting directives for your visualizations. {
Plotly runs on all systems, and can be installed in one line. from plotly.graph_objs import Scatter, Layout # Trace 1: squares
Installing Plotly from plotly import offline 'type': 'scatter',
'x': x_values,
$ python -m pip install --user plotly x_values = list(range(11)) 'y': squares,
squares = [x**2 for x in x_values] 'name': 'Squares',
Line graphs, scatter plots, and bar graphs },
data = [Scatter(x=x_values, y=squares)] {
To make a plot with Plotly, you specify the data and then
# Trace 2: cubes
pass it to a graph object. The data is stored in a list, so you
# Add a title, and a label for each axis. 'type': 'scatter',
can add as much data as you want to any graph. In offline
title = 'Square Numbers' 'x': x_values,
mode, the output should open automatically in a browser 'y': cubes,
x_axis_config = {'title': 'x'}
window. 'name': 'Cubes',
y_axis_config = {'title': 'Square of x'}
Making a line graph },
A line graph is a scatter plot where the points are connected. Plotly my_layout = Layout(title=title, ]
generates JavaScript code to render the plot file. If you're curious to xaxis=x_axis_config, yaxis=y_axis_config)
see the code, open the [Link] file in a text editor after running [Link](data,
this program. [Link]( filename='squares_cubes.html')
from plotly.graph_objs import Scatter {'data': data, 'layout': my_layout},
from plotly import offline filename='[Link]') Online resources
The Plotly documentation is extensive and well-organized.
# Define the data. Specifying complex data Start with the overview at [Link]/python/. Here you can
x_values = list(range(11)) see an example of all the basic chart types, and click on any
Data as a dictionary
squares = [x**2 for x in x_values] example to see a relevant tutorial.
Plotly is highly customizable, and most of that flexibility comes from
representing data and formatting directives as a dictionary. Here is Then take a look at the Python Figure Reference, at
# Pass the data to a graph object, and store it the same data from the previous examples, defined as a dictionary. [Link]/python/reference/. Check out the Figure Data
# in a list. Defining the data as a dictionary also allows you to specify more Structure in Python page as well, at [Link]/python/figure-
data = [Scatter(x=x_values, y=squares)] information about each series. Anything that pertains to a specific structure/.
data series such as markers, lines, and point labels, goes in the
# Pass the data and a filename to plot(). data dictionary. Plotly has several ways of specifying data, but
[Link](data, filename='[Link]') internally all data is represented in this way.
Making a scatter plot data = [{
'type': 'scatter',
Python Crash Course
To make a scatter plot, use the mode='markers' argument to tell
Plotly to only display the markers. 'x': x_values, A Hands-on, Project-Based
'y': squares, Introduction to Programming
data = [Scatter(x=x_values, y=squares, 'mode': 'markers',
mode='markers')] [Link]/pythoncrashcourse2e
}]
Specifying complex layouts Specifying complex layouts (cont.) Plotting global datasets
You can also specify the layout of your visualization as a Using a colorscale Plotly has a variety of mapping tools. For example, if you
dictionary, which gives you much more control of the overall Colorscales are often used to show variations in large datasets. In have a set of points represented by latitude and longitude,
layout. Plotly, colorscales are set in the marker dictionary, nested inside a you can create a scatter plot of those points overlaying a
data dictionary. map.
Layout as a dictionary
Here is the same layout we used earlier, written as a dictionary. data = [{ The scattergeo chart type
Simple elements such as the title of the chart are just key-value 'type': 'scatter', Here's a map showing the location of three of the higher peaks in
pairs. More complex elements such as axes, which can have many 'x': x_values, North America. If you hover over each point, you'll see its location
of their own settings, are nested dictionaries. 'y': squares, and the name of the mountain.
my_layout = { 'mode': 'markers',
from plotly import offline
'title': 'Square Numbers', 'marker': {
'xaxis': { 'colorscale': 'Viridis',
# Points in (lat, lon) format.
'title': 'x', 'color': squares,
peak_coords = [
}, 'colorbar': {'title': 'Value'},
(63.069, -151.0063),
'yaxis': { },
(60.5671, -140.4055),
'title': 'Square of x', }]
(46.8529, -121.7604),
}, ]
} Using Subplots
It's often useful to have multiple plots share the same axes. # Make matching lists of lats, lons,
A more complex layout # and labels.
Here is a layout for the same data, with more specific formatting
This is done using the subplots module.
lats = [pc[0] for pc in peak_coords]
directives in the data and layout dictionaries. Adding subplots to a figure lons = [pc[1] for pc in peak_coords]
from plotly.graph_objs import Scatter To use the subplots module, make a figure to hold all the charts peak_names = ['Denali', 'Mt Logan',
from plotly import offline that will be made. Then use the add_trace() method to add each 'Mt Rainier']
data series to the overall figure.
For more help, see the documentation at [Link]/python/subplots/.
x_values = list(range(11)) data = [{
squares = [x**2 for x in x_values] from [Link] import make_subplots 'type': 'scattergeo',
from plotly.graph_objects import Scatter 'lon': lons,
data = [{ from plotly import offline 'lat': lats,
'type': 'scatter', 'marker': {
'x': x_values, x_values = list(range(11)) 'size': 20,
'y': squares, squares = [x**2 for x in x_values] 'color': '#227722',
'mode': 'markers', cubes = [x**3 for x in x_values] },
'marker': { 'text': peak_names,
'size': 10, # Make two subplots, sharing a y-axis. }]
'color': '#6688dd', fig = make_subplots(rows=1, cols=2,
}, shared_yaxes=True) my_layout = {
}] 'title': 'Selected High Peaks',
data = { 'geo': {
my_layout = { 'type': 'scatter', 'scope': 'north america',
'title': 'Square Numbers', 'x': x_values, 'showland': True,
'xaxis': { 'y': squares, 'showocean': True,
'title': 'x', } 'showlakes': True,
'titlefont': {'family': 'monospace'}, fig.add_trace(data, row=1, col=1) 'showrivers': True,
}, },
'yaxis': { data = { }
'title': 'Square of x', 'type': 'scatter',
'titlefont': {'family': 'monospace'}, 'x': x_values, [Link](
}, 'y': cubes, {'data': data, 'layout': my_layout},
} } filename='[Link]')
fig.add_trace(data, row=1, col=2)
[Link](
{'data': data, 'layout': my_layout}, [Link](fig, filename='[Link]') More cheat sheets available at
filename='[Link]')
[Link]/pcc_2e/