#!/usr/bin/env python
# coding: utf-8
# #### New to Plotly?
# Plotly's Python library is free and open source! [Get started](https://plotly.com/python/getting-started/) by downloading the client and [reading the primer](https://plotly.com/python/getting-started/).
# You can set up Plotly to work in [online](https://plotly.com/python/getting-started/#initialization-for-online-plotting) or [offline](https://plotly.com/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plotly.com/python/getting-started/#start-plotting-online).
# We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started!
# #### Version Check
# Note: Linear fits are available in version 1.9.2+
# Run `pip install plotly --upgrade` to update your Plotly version
# In[1]:
import plotly
plotly.__version__
# ### Linear Fit
# In[2]:
# Learn about API authentication here: https://plotly.com/python/getting-started
# Find your api_key here: https://plotly.com/settings/api
import plotly.plotly as py
import plotly.graph_objs as go
# Scientific libraries
from numpy import arange,array,ones
from scipy import stats
xi = arange(0,9)
A = array([ xi, ones(9)])
# (Almost) linear sequence
y = [19, 20, 20.5, 21.5, 22, 23, 23, 25.5, 24]
# Generated linear fit
slope, intercept, r_value, p_value, std_err = stats.linregress(xi,y)
line = slope*xi+intercept
# Creating the dataset, and generating the plot
trace1 = go.Scatter(
x=xi,
y=y,
mode='markers',
marker=go.Marker(color='rgb(255, 127, 14)'),
name='Data'
)
trace2 = go.Scatter(
x=xi,
y=line,
mode='lines',
marker=go.Marker(color='rgb(31, 119, 180)'),
name='Fit'
)
annotation = go.Annotation(
x=3.5,
y=23.5,
text='$R^2 = 0.9551,\\Y = 0.716X + 19.18$',
showarrow=False,
font=go.Font(size=16)
)
layout = go.Layout(
title='Linear Fit in Python',
plot_bgcolor='rgb(229, 229, 229)',
xaxis=go.XAxis(zerolinecolor='rgb(255,255,255)', gridcolor='rgb(255,255,255)'),
yaxis=go.YAxis(zerolinecolor='rgb(255,255,255)', gridcolor='rgb(255,255,255)'),
annotations=[annotation]
)
data = [trace1, trace2]
fig = go.Figure(data=data, layout=layout)
py.plot(fig, filename='Linear-Fit-in-python')
# In[4]:
from IPython.display import display, HTML
display(HTML(''))
display(HTML(''))
get_ipython().system(' pip install git+https://github.com/plotly/publisher.git --upgrade')
import publisher
publisher.publish(
'linear-fits.ipynb', 'python/linear-fits/', 'Linear Fit',
'Create a linear fit / regression in Python and add a line of best fit to your chart.',
title = 'Linear Fit',
name = 'Linear Fit',
has_thumbnail='true', thumbnail='thumbnail/linear_fit.jpg',
language='python', page_type='example_index',
display_as='statistics', order=10,
ipynb= '~notebook_demo/139')
# In[ ]: