Show Sidebar Hide Sidebar

Comparison of LDA and PCA 2D projection of Iris dataset in Scikit-learn

The Iris dataset represents 3 kind of Iris flowers (Setosa, Versicolour and Virginica) with 4 attributes: sepal length, sepal width, petal length and petal width.

Principal Component Analysis (PCA) applied to this data identifies the combination of attributes (principal components, or directions in the feature space) that account for the most variance in the data. Here we plot the different samples on the 2 first principal components.

Linear Discriminant Analysis (LDA) tries to identify attributes that account for the most variance between classes. In particular, LDA, in contrast to PCA, is a supervised method, using known class labels.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!


In [1]:
import sklearn


This tutorial imports PCA and LinearDiscriminantAnalysis.

In [2]:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly import tools

from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis


In [3]:
iris = datasets.load_iris()

X =
y =
target_names = iris.target_names

pca = PCA(n_components=2)
X_r =

lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 =, y).transform(X)

# Percentage of variance explained for each components
print('explained variance ratio (first two components): %s'
      % str(pca.explained_variance_ratio_))

colors = ['navy', 'turquoise', 'darkorange']
explained variance ratio (first two components): [ 0.92461621  0.05301557]

Plot Results

In [4]:
fig = tools.make_subplots(rows=1, cols=2,
                          subplot_titles=('PCA of IRIS dataset',
                                          'LDA of IRIS dataset')
This is the format of your plot grid:
[ (1,1) x1,y1 ]  [ (1,2) x2,y2 ]

In [5]:
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
    pca = go.Scatter(x=X_r[y == i, 0], 
                     y=X_r[y == i, 1], 
    fig.append_trace(pca, 1, 1)
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
    lda = go.Scatter(x=X_r2[y == i, 0], 
                     y=X_r2[y == i, 1],
    fig.append_trace(lda, 1, 2)
for i in map(str, range(1, 3)):
    x = 'xaxis' + i
    y = 'yaxis' + i
    fig['layout'][x].update(zeroline=False, showgrid=False)
    fig['layout'][y].update(zeroline=False, showgrid=False)
In [6]:
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.