How to annotate labels in a 3D matplotlib scatter plot?

2017-03-20 23:29:18

I have made a 3x3 PCA matrix with sklearn.decomposition PCA and plotted it to a matplotlib 3D scatter plot.

How can I annotate labels near the points/marker? Here is my code:

from mpl_toolkits.mplot3d import axes3d

import matplotlib.pyplot as plt

%matplotlib notebook

fig = plt.figure()

ax = fig.gca(projection='3d')


existing_df_3dx['PC0'], existing_df_3dx['PC1'], existing_df_3dx['PC2'], # data

s=60 # marker size


Also, if you know of a better way to plot a 3D PCA, please post your code


A solution provided from Stack Overflow:

for i in range(len(data_df_3dx)):

x, y, z = data_df_3dx.iloc[i]['PC1'], data_df_3dx.iloc[i]['PC2'], data_df_3dx.iloc[i]['PC3']

ax.scatter(x, y, z)

#now that you have the coordinates you can apply whatever text you need. I'm

#assuming you want the index, but you could also pass a column name if needed

ax.text(x, y, z, '{0}'.format(d

  • In the following posts [1], [2] the plotting of 3D arrows in matplotlib is discussed.

    Similarly Annotation3D class (inherited from Annotation) can be created:

    from mpl_toolkits.mplot3d.proj3d import proj_transform

    from matplotlib.text import Annotation

    class Annotation3D(Annotation):

    '''Annotate the point xyz with text s'''

    def __init__(self, s, xyz, *args, **kwargs):

    Annotation.__init__(self,s, xy=(0,0), *args, **kwargs)

    self._verts3d = xyz

    def draw(self, renderer):

    xs3d, ys3d, zs3d = self._verts3d

    xs, ys, zs = proj_transform(xs3d, ys3d, zs3d, renderer.M)


    Annotation.draw(self, renderer)

    Further, we can define the annotate3D() function:

    def annotate3D(ax, s, *args, **kwargs):

    '''add anotation text s to to Axes3d ax'''

    tag = Annotation3D(s, *args, **kwargs)


    Using this function annotation tags can be added to Axes3d as in example bellow:

    3D graph example


    2017-03-21 00:31:16