How to plot a density curve in python using plotly?
Specifically, I would like to do that for some standard densities.
UPDATE:
So far, the best way of achieving what I ask for (in a Jupyter notebook):
import numpy as np
from scipy import stats
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)
Plotting
xrange = np.arange(-4.5,5,0.0025)
norm = go.Scatter(x=xrange,
y=stats.norm(loc=0, scale=1).pdf(xrange),
mode='lines',
line=dict(width=1.5),
name='Normal',
)
lognorm = go.Scatter(x=xrange[xrange>0],
y=stats.lognorm(s=1, loc=0, scale=1).pdf(xrange[xrange>0]),
mode='lines',
line=dict(width=1.5),
name='Lognormal',
)
cauchy = go.Scatter(x=xrange,
y=stats.cauchy(loc=0, scale=1).pdf(xrange),
mode='lines',
line=dict(width=1.5),
name='Cauchy',
)
data = [norm, lognorm, cauchy]
iplot(data, show_link=False)
I was looking for an easy, parsimonious way, as it is done in Mathematica for instance:
Plot[{PDF[NormalDistribution[], x], PDF[LogNormalDistribution[0, 1], x], PDF[CauchyDistribution[], x]}, {x, -4.5, 4.5}]
The code below uses gaussian_kde
. The plots are in iplot()
, plotly
, as well as matplotlib
, and seaborn
to compare them together. (Jupyter Notebook 5.0.0
, Python 3.6.6
)
# Import libraries
import pandas as pd
import numpy as np
from numpy import linspace
import seaborn as sns
from matplotlib import pyplot as plt
import scipy.stats as st
from scipy.stats.kde import gaussian_kde
import plotly.offline as pyo
import plotly.graph_objs as go
from plotly import __version__
%matplotlib inline
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
init_notebook_mode(connected=True)
cf.go_offline()
Create sample data
np.random.seed(1)
data = pd.DataFrame(np.random.randn(500,1), columns=['x'])
data.head(2)
Calculate kde
values and put them in a dataframe
df = pd.DataFrame({'x_range': linspace(min(data['x']), max(data['x']), len(data['x'])),
'x_kde': kde(x_range)
})
Use iplot()
to create plot
df.iplot(x='x_range', y='x_kde')
Use plotly
to create plots
Note: This plot opens in a new browser window
# Create trace, data and layout
trace = go.Scatter(x=df['x_range'],y=df['x_kde'], mode='markers',name='markers')
data = [trace]
layout = go.Layout(title='Line Chart')
# Plot figure
fig = go.Figure(data=data, layout=layout)
pyo.offline.plot(fig)
Use Seaborn
to plot
sns.distplot(data['x'], hist=False, rug=True)
Use base plot
data['x'].plot.density()
Use Matplotlib
to plot
kde = gaussian_kde(data.x)
x_range = linspace(min(data.x), max(data.x), len(data.x))
plt.plot(x_range, kde(x_range) )
Edit . . . . . . . . . . . . . . . . . .
One approach would be to compile all values in a dataframe
and then send it to iplot()
in one line.
Create dataframe
df = pd.DataFrame({'xrange':np.arange(-4.5,5,0.0025)})
df['norm_x'] = stats.norm(loc=0, scale=1).pdf(df['xrange'])
df['cauchy_x'] = stats.cauchy(loc=0, scale=1).pdf(df['xrange'])
df['lognormal_x'] = stats.lognorm(s=1, loc=0, scale=1).pdf(df['xrange'])
df = pd.DataFrame({'xrange':xrange, 'norm_x':norm_x, 'cauchy_x':cauchy_x, 'lognormal_x':lognormal_x})
Plot using iplot()
df.iplot(x='xrange', y=['norm_x', 'cauchy_x', 'lognormal_x'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With