# Plotly Charting

By pjain      Published Nov. 30, 2019, 10:53 p.m. in blog AI-Analytics-Data

# Plotly QuikStart

## Install, Pragmatics

```pip install plotly #installs 4.3.0
```

## Ex 101 - Simple charts

```import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
```

## plotly.express 101 - simple arrays

With px.line or px.scatter each data point is represented as a vertex (which location is given by the x and y columns) of a polyline mark in 2D space.

```# x and y given as array_like objects
import plotly.express as px
fig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])
fig.show()
```

## DataFrame - plotly.express

```import plotly.express as px
import numpy as np

# x and y given as DataFrame columns
iris = px.data.iris() # iris is a pandas DataFrame # setting size of points
fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species",
size='petal_length', hover_data=['petal_width'])
fig.show() # [see graph@](https://plot.ly/python/line-and-scatter/)

import plotly.express as px
t = np.linspace(0, 2*np.pi, 100)
fig = px.line(x=t, y=np.cos(t), labels={'x':'t', 'y':'cos(t)'})
fig.show()

# Multiple lines - one per country
gapminder = px.data.gapminder().query("continent == 'Oceania'")
fig = px.line(gapminder, x='year', y='lifeExp', color='country')
fig.show()
```

## Writing out to HTML

```import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.write_html('first_figure.html', auto_open=True)
```

# Plotly 101

• plotly.py version 4 is "offline" only, and does not include any functionality for uploading figures or data to cloud services.

# Regression with Plotly

## Least Squares Conceptual

Plotly Express is the easy-to-use, high-level interface to Plotly, which operates on "tidy" data. With Plotly Express you can add linear Ordinary Least Squares (OLS) regression trendlines Hovering over the trendline will show the equation of the line and its R-squared value.

• In order to do so, you will need to install statsmodels and its dependencies.
• Plotly Express allows you to add Ordinary Least Squares regression trendline to scatterplots with the trendline argument.

import plotly.express as px tips = px.data.tips() fig = px.scatter(tips, x="total_bill", y="tip", trendline="ols") fig.show()

## Non-linear Regression

Non-linear Locally Weighted Scatterplot Smoothing (LOEWSS) trendlines to scatterplots in Python.

# Plotly with Jupyter Notebook

## jupyter notebook examples

```\$ pip install "notebook&gt;=5.3" "ipywidgets&gt;=7.2"
\$ jupyter notebook
import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.show()
# or using FigureWidget object - output right into notebook
fig = go.FigureWidget(data=go.Bar(y=[2, 3, 1]))
fig
```

# Plotly Dash

• Dash is a framework for building analytic web apps - No JavaScript required - enterprise and open source versions.