Search code examples
pythonpandasdataframe3dscatter

3d plot/scatter xyz coordinates from pandas data frame


i have a pd df in the following form:

x y z label
0.0 0.0 0.0 1.0
0.0 0.0 1.0 1.0
0.0 0.0 2.0 1.0
0.0 0.0 3.0 1.0
0.0 0.0 4.0 1.0

the label is a result of clusturing but i can't seem to find a proper way to do a 3D plt.scatter on the df. any ideas? (the data frame is much bigger than this)


Solution

  • I tried my best. Maybe it will help you out.

    import pandas as pd
    import numpy as np
    

    Your data table

    df = {'x': [0, 0, 0, 0, 0],
          'y': [0, 0, 0, 0, 0],
          'z': [0, 1, 2, 3, 4],
      'label': ['1', '1', '1', '1', '1'] }
    
    df = pd.DataFrame(data)
    df
    

    #Creating a 3d scatter plot 
    
    def create_3d_scatter(df):
        import matplotlib.pyplot as plt
        import numpy as np
        from mpl_toolkits.mplot3d import Axes3D
    
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        ax.scatter(df['x'], df['y'], df['z'], c=df['label'])
        plt.show()
    


    This is the according google colab file with the code