简体   繁体   中英

How to set legend outside three-dimensional axes in matplotlib?

I am working with a basic 3D scatterplot in matplotlib. A simple example of the code is the following:

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt
import numpy as np

XX = np.array([[1,6,7,3,2],[8,11,7,5,12],[2,7,1,30,12],[15,3,17,2,1]])

fig = plt.figure()
ax = plt.axes(projection='3d')

xs = XX[indx, 0]
ys = XX[indx, 1]
zs = XX[indx, 2]


for i in range(11):
    ax.scatter3D(xs, ys, zs, c='b', marker='o', label='item'+str(i), s=100.5, alpha=1)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.title('Number of Components = 3')
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=7)
plt.tight_layout()
plt.show()

Following is my output plot:

在此处输入图片说明

In my output plot, the legend overlaps with the label for Z-axis. I want to place the legend outside of the three dimensional axis box, preferably to the right of the plot (ie to the right of ZLabel) such that it doesn't overlap with anything . How can I do that?

The general strategy to place the legend out of the plot is shown in How to put the legend out of the plot

Here you may want to leave some more space to the right and move the legend even further to the right

fig.tight_layout()
fig.subplots_adjust(right=0.8)
ax.legend(loc='center left', bbox_to_anchor=(1.07, 0.5), fontsize=7)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM