pythonmatplotlibscatter3d

How to show legend in Pyplot Scatter 3D


I am making a Scatter 3D pyplot using arrays with float numbers

x = c_icrs.galactic.cartesian.x.value
y = c_icrs.galactic.cartesian.y.value
z = c_icrs.galactic.cartesian.z.value

Where x,y,z are:

x:array([ -65.1525587 ,   -1.76919179,    3.87621068, -193.69267564, -8.49586587])
y:array([ 99.25870537,  -1.91258061,   1.04225814, -96.36986244, 9.24999572])
z:array([ 59.09744472,  -0.40753885,  10.51755917, -64.43345929, 21.251354  ])

The plot:

fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(projection='3d')
ax.set_title("Title")
ax.set_xlabel('X [pc]')
ax.set_ylabel('Y [pc]')
ax.set_zlabel('Z [pc]')



scatter1 = ax.scatter3D(x,y,z, s = 400, marker = '*',c=[1,2,3,4,5])
legend1 = ax.legend(['a','b','c','d','e'], title="Legend")

scatter2 = ax.scatter3D(0,0,0, s = 200, color = 'orange')

enter image description here

How do I add the other markers on the legend? only the first one is showing (a)


Solution

  • First, change your legend declaration to the following legend1. Then, add that legend to the ax with add_artist. Lastly, add a label name to your second scatter plot and call plt.legend() to show both. You can also add custom labels to each element legend (if you want abcde instead of 12345). If not, then just replace *[scatter1.legend_elements()[0],['a','b','c','d','e']] with *scatter1.legend_elements().

    fig = plt.figure(figsize=(8,8))
    ax = fig.add_subplot(projection='3d')
    ax.set_title("Title")
    ax.set_xlabel('X [pc]')
    ax.set_ylabel('Y [pc]')
    ax.set_zlabel('Z [pc]')
    
    
    
    scatter1 = ax.scatter3D(x,y,z, s = 400, marker = '*',c=[1,2,3,4,5])
    legend1 = ax.legend(*[scatter1.legend_elements()[0],['a','b','c','d','e']], 
                        title="Legend", loc='upper left')
    ax.add_artist(legend1)
    
    scatter2 = ax.scatter3D(0,0,0, s = 200, color = 'orange', label='Dot')
    plt.legend()
    plt.show()
    

    enter image description here