Skip to content

Instantly share code, notes, and snippets.

@johntyree
Created February 3, 2014 15:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johntyree/8785541 to your computer and use it in GitHub Desktop.
Save johntyree/8785541 to your computer and use it in GitHub Desktop.
Create a scree plot showing eigval contribution
#!/usr/bin/env python
# coding: utf8
# GistID: 8785541
from __future__ import division
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# Make a random array and then make it positive-definite
A = np.random.randn(6, 9)
A = np.asmatrix(A) * np.asmatrix(A.T)
U, S, V = np.linalg.svd(A)
eigvals = S**2 / np.cumsum(S)[-1]
eigvals2 = S**2 / np.sum(S)
assert (eigvals == eigvals2).all()
fig = plt.figure(figsize=(8,5))
sing_vals = np.arange(len(eigvals)) + 1
plt.plot(sing_vals, eigvals, 'ro-', linewidth=2)
plt.title('Scree Plot')
plt.xlabel('Principal Component')
plt.ylabel('Eigenvalue')
#I don't like the default legend so I typically make mine like below, e.g.
#with smaller fonts and a bit transparent so I do not cover up data, and make
#it moveable by the viewer in case upper-right is a bad place for it
leg = plt.legend(['Eigenvalues from SVD'], loc='best', borderpad=0.3,
shadow=False, prop=matplotlib.font_manager.FontProperties(size='small'),
markerscale=0.4)
leg.get_frame().set_alpha(0.4)
leg.draggable(state=True)
plt.show()
def main():
"""Run main."""
return 0
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment