0% found this document useful (0 votes)
22 views

Beginners Python Cheat Sheet PCC Plotly BW

Uploaded by

amkslade101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Beginners Python Cheat Sheet PCC Plotly BW

Uploaded by

amkslade101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Beginner's Python

Line graphs, scatter plots, and bar graphs Further customizations


(cont.) You can make a wide variety of further customizations to
a plot using the update methods. For example, update_
Making a bar graph
Cheat Sheet - Plotly fig = px.bar(x=x_values, y=squares)
layout() gives you control of many formatting options.
Using update_layout()
Here the update_layout() method is used to change the font
Initial customizations sizes, and change the tick mark spacing on the x-axis.
What is Plotly? The functions that generate plots also accept parameters import plotly.express as px
Data visualization involves exploring data through that specify titles, labels, and other formatting directives for
visual representations. Plotly helps you make visually your visualizations. x_values = list(range(11))
appealing representations of the data you’re working Adding a title and axis labels squares = [x**2 for x in x_values]
with. Plotly is particularly well suited for visualizations The title is a string. The labels dictionary lets you specify which
that will be presented online, because it supports aspects of the plot will have custom labels. title = "Square Numbers"
labels = {'x': 'Value', 'y': 'Square of Value'}
interactive elements. import plotly.express as px
Plotly express lets you see a basic version of your fig = px.scatter(
plot with just a few lines of code. Once you know the # Define the data. x=x_values,
plot works for your data, you can refine the style of x_values = list(range(11)) y=squares,
squares = [x**2 for x in x_values] ...
your plot.
)
# Visualize the data.
Installing Plotly title = "Square Numbers" fig.update_layout(
Plotly Express requires the pandas library. labels = {'x': 'Value', 'y': 'Square of Value'} title_font_size=30,
Installing Plotly with pip xaxis_title_font_size=24,
fig = px.scatter(x=x_values, y=squares, xaxis_dtick=1,
$ python -m pip install --user plotly title=title, labels=labels) xaxis_tickfont_size=16,
$ python -m pip install --user pandas fig.show() yaxis_title_font_size=24,
More customizations in the plotting call yaxis_tickfont_size=16,
Line graphs, scatter plots, and bar graphs Plotly Express was designed to give you as much control as
)
To make a plot with Plotly Express, you specify the data and possible, using as little code as possible. Here's a small example of
then create a fig object. The call to fig.show() opens the how much can be customized within a single plotting call. fig.show()
plot in a new browser tab. You have a plot in just two lines of Most of these arguments can be single values, or sequences that
code! match the size of the overall dataset. Plotly Express documentation
Making a line graph import plotly.express as px Plotly's documentation is extensive and well-organized.
Plotly generates JavaScript code to render the plot file. If you're There's a lot of it, though, so it can be hard to know where to
curious to see the code, open your browser's inspector tool when x_values = list(range(11)) begin. Start with an overview of Plotly Express at plotly.com/
the plot opens. squares = [x**2 for x in x_values] python/plotly-express. This page itself is helpful; make sure
you also click on the documentation for the kinds of plots
import plotly.express as px title = "Square Numbers" you use most often. These lead to pages full of discussions
labels = {'x': 'Value', 'y': 'Square of Value'} and examples.
# Define the data.
x_values = list(range(11)) Also see the Python API reference for plotly at plotly.
fig = px.scatter( com/python-api-reference. This is a reference page showing
squares = [x**2 for x in x_values] x=x_values,
all the different kinds of plots you can make with Plotly. If you
y=squares,
# Visualize the data. click on any of the links, you can see all the arguments that
title=title,
fig = px.line(x=x_values, y=squares) can be included in plotting calls.
labels=labels,
fig.show() size=squares,

Python Crash Course


Making a scatter plot color=squares,
opacity=0.5,
To make a scatter plot, change line() to scatter(). This is the
point of Plotly Express; you can easily see your data in a variety of
width=1200, A Hands-on, Project-Based
ways before committing to a more specific styling options. height=800, Introduction to Programming
)
fig = px.scatter(x=x_values, y=squares) ehmatthes.github.io/pcc_3e
fig.show()
Using a predefined theme Using Subplots Plotting global datasets
A theme is a set of styles applied to a visualization in Plotly. It's often useful to have multiple plots share the same axes. Plotly has a variety of mapping tools. For example, if you
Themes are implemented with templates. This is done using the subplots module. have a set of points represented by latitude and longitude,
you can create a scatter plot of those points overlaying a
Using a theme Adding subplots to a figure
map.
To use the subplots module, make a figure to hold all the charts
import plotly.express as px
that will be made. Then use the add_trace() method to add each The scattergeo chart type
data series to the overall figure. Here's a map showing the location of three of the higher peaks in
# Define the data. All individual plots need to be made using the graph_objects
x_values = list(range(11)) North America. If you hover over each point, you'll see its location
module. and the name of the mountain.
squares = [x**2 for x in x_values]
from plotly.subplots import make_subplots import plotly.express as px
# Visualize the data. import plotly.graph_objects as go
title = "Square Numbers" # Points in (lat, lon) format.
labels = {'x': 'Value', 'y': 'Square of Value'} x_values = list(range(11)) peak_coords = [
squares = [x**2 for x in x_values] (63.069, -151.0063),
fig = px.scatter(x=x_values, y=squares, cubes = [x**3 for x in x_values] (60.5671, -140.4055),
title=title, labels=labels, (46.8529, -121.7604),
template='plotly_dark') # Make two subplots, sharing a y-axis. ]
fig.show() fig = make_subplots(rows=1, cols=2,
shared_yaxes=True) # Make matching lists of lats, lons,
Viewing all available themes # and labels.
>>> import plotly.io as pio # Start by plotting the square numbers. lats = [pc[0] for pc in peak_coords]
>>> pio.templates squares_trace = go.Scatter(x=x_values, lons = [pc[1] for pc in peak_coords]
Templates configuration y=squares)
----------------------- fig.add_trace(squares_trace, row=1, col=1) peak_names = [
Default template: 'plotly' "Denali",
Available templates: # Add a new trace for the cubes. "Mt Logan",
['ggplot2', 'seaborn',..., cubes_trace = go.Scatter(x=x_values, y=cubes) "Mt Rainier"
'ygridoff', 'gridon', 'none'] fig.add_trace(cubes_trace, row=1, col=2) ]
elevations = [20_000, 18_000, 14_000]
title = "Squares and Cubes"
Adding traces to a Plotly Express plot fig.update_layout(title_text=title) # Generate initial map.
In Plotly, a trace is a dataset that can be plotted on a title = "Selected High Peaks"
chart. You can add traces to existing Plotly Express plots. fig.show() fig = px.scatter_geo(
Additional plots need to be specified using the graph_objects lat=lats,
module. Further documentation lon=lons,
title=title,
Using fig.add_trace() After exploring the Plotly Express documenation, look at
projection="natural earth",
Styling Plotly Express Figures in Python, at plotly.com/
import plotly.express as px text=peak_names,
python/styling-plotly-express. This explains all the ways
import plotly.graph_objects as go size=elevations,
you can style and format plots. After that, the Python Figure scope="north america",
days = list(range(1, 10)) Reference (plotly.com/python/reference/index) will be much )
highs = [60, 63, 68, 70, 68, 70, 66, 62, 64] more useful. It shows you all the possible settings you can
lows = [51, 54, 53, 57, 54, 56, 52, 53, 49] change, with examples for each. # Customize formatting options.
Make sure you read about "magic underscores" in Plotly, fig.update_layout(titlefont_size=24)
# Start by plotting low temperaturs. at plotly.com/python/creating-and-updating-figures. They fig.update_traces(
fig = px.line(x=days, y=lows) take a little getting used to, but once you're familiar with textposition="middle right",
the syntax they make it much easier to specify exactly the textfont_size=18,
# Add a new trace for the high temperatures. settings you want to modify. )
new_trace = go.Scatter(x=days, y=highs,
mode='lines') If you're using subplots, read Subplots in Python at plotly. fig.show()
fig.add_trace(new_trace) com/python/subplots. Also look at Graph Objects in Python
at plotly.com/python/graph-objects, which are used to make
fig.show() individual plots in a subplot. Weekly posts about all things Python
mostlypython.substack.com

You might also like