Created
July 7, 2016 21:00
-
-
Save shoeffner/96adf28a4542a4564e1a7d2c2d898126 to your computer and use it in GitHub Desktop.
Draw points (potentially with an image as background) and get the principal components drawn nicely. Horrible code though.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Left click adds points. | |
Right click clears the image. | |
Use the fancy figure window to store plots. | |
If 2+ points were added, principal components are drawn at the center of mass. | |
""" | |
import matplotlib | |
matplotlib.use('Qt5Agg') | |
import matplotlib.pyplot as plt | |
import numpy as np | |
from sklearn.decomposition.pca import PCA | |
# UNCOMMENT AND ADD FILENAME TO DRAW IMAGE AS BACKGROUND | |
# IMG = plt.imread('data_image.png') | |
DATA = [] | |
def onclick(event): | |
plt.figure('myfig') | |
if event.button == 1: | |
DATA.append((event.xdata, event.ydata)) | |
plt.clf() | |
plt.plot() | |
try: | |
plt.imshow(IMG) | |
except NameError: | |
plt.xlim([0, 1]) | |
plt.ylim([0, 1]) | |
plt.scatter(*zip(*DATA), c='orange') | |
if len(DATA) > 1: | |
pca = PCA(2).fit(DATA) | |
pcs = (pca.components_.T * pca.explained_variance_).T | |
center = np.mean(np.array(DATA), 0) | |
plt.quiver(*center, *pcs.T) | |
else: | |
DATA.clear() | |
plt.clf() | |
plt.plot() | |
try: | |
plt.imshow(IMG) | |
except NameError: | |
plt.xlim([0, 1]) | |
plt.ylim([0, 1]) | |
plt.draw() | |
if __name__ == '__main__': | |
FIG = plt.figure('myfig') | |
plt.plot() | |
try: | |
plt.imshow(IMG) | |
except NameError: | |
plt.xlim([0, 1]) | |
plt.ylim([0, 1]) | |
FIG.canvas.mpl_connect('button_press_event', onclick) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment