.. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_packages_scikit-learn_auto_examples_plot_pca.py: =============== Demo PCA in 2D =============== Load the iris data .. code-block:: python from sklearn import datasets iris = datasets.load_iris() X = iris.data y = iris.target Fit a PCA .. code-block:: python from sklearn.decomposition import PCA pca = PCA(n_components=2, whiten=True) pca.fit(X) Project the data in 2D .. code-block:: python X_pca = pca.transform(X) Visualize the data .. code-block:: python target_ids = range(len(iris.target_names)) from matplotlib import pyplot as plt plt.figure(figsize=(6, 5)) for i, c, label in zip(target_ids, 'rgbcmykw', iris.target_names): plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, label=label) plt.legend() plt.show() .. image:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_pca_001.png :class: sphx-glr-single-img **Total running time of the script:** ( 0 minutes 0.020 seconds) .. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_pca.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download :download:`Download Python source code: plot_pca.py ` .. container:: sphx-glr-download :download:`Download Jupyter notebook: plot_pca.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_