Skip to content

Instantly share code, notes, and snippets.

@srishtis
Created October 5, 2018 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srishtis/5c7f55e8fd4043a76ab06d085d491ea8 to your computer and use it in GitHub Desktop.
Save srishtis/5c7f55e8fd4043a76ab06d085d491ea8 to your computer and use it in GitHub Desktop.
Plot the explained variance in iris dataset
# PLOTTING THE EXPLAINED VARIANCE CHARTS
##################################
#USING THE COVARIANCE MATRIX
##################################
tot = sum(eig_vals1)
explained_variance1 = [(i / tot)*100 for i in sorted(eig_vals1, reverse=True)]
cum_explained_variance1 = np.cumsum(explained_variance1)
trace3 = Bar(
x=['PC %s' %i for i in range(1,5)],
y=explained_variance1,
showlegend=False)
trace4 = Scatter(
x=['PC %s' %i for i in range(1,5)],
y=cum_explained_variance1,
name='cumulative explained variance')
data2 = Data([trace3, trace4])
layout2=Layout(
yaxis=YAxis(title='Explained variance in percent'),
title='Explained variance by different principal components using the covariance matrix')
fig2 = Figure(data=data2, layout=layout2)
py.iplot(fig2)
##################################
#USING CORRELATION MATRIX
##################################
tot = sum(eig_vals3)
explained_variance = [(i / tot)*100 for i in sorted(eig_vals3, reverse=True)]
cum_explained_variance = np.cumsum(explained_variance)
trace1 = Bar(
x=['PC %s' %i for i in range(1,5)],
y=explained_variance,
showlegend=False)
trace2 = Scatter(
x=['PC %s' %i for i in range(1,5)],
y=cum_explained_variance,
name='cumulative explained variance')
data = Data([trace1, trace2])
layout=Layout(
yaxis=YAxis(title='Explained variance in percent'),
title='Explained variance by different principal components using the correlation matrix')
fig = Figure(data=data, layout=layout)
py.iplot(fig)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment