简体   繁体   English

向曲面图添加图例

[英]Adding legend to a surface plot

I am trying to add legend to a surface plot but unable to do so.我正在尝试将图例添加到曲面图中,但无法这样做。 Here is the code.这是代码。

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

def fun(x, y):
  return 0.063*x**2 + 0.0628*x*y - 0.15015876*x + 96.1659*y**2 - 74.05284306*y  +      14.319143466051


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-1.0, 1.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.plot(color='red',label='Lyapunov function on XY plane',linewidth=4)  # Adding legend

plt.show()

Kindly help.请帮助。 Thanks in advance.提前致谢。

It is not trivial to make a legend in a 3D axis. 在3D轴上制作图例并非易事。 You can use the following hack: 您可以使用以下hack:

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

def fun(x, y):
  return 0.063*x**2 + 0.0628*x*y - 0.15015876*x + 96.1659*y**2 - 74.05284306*y  +      14.319143466051


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-1.0, 1.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
fake2Dline = mpl.lines.Line2D([0],[0], linestyle="none", c='b', marker = 'o')
ax.legend([fake2Dline], ['Lyapunov function on XY plane'], numpoints = 1)
plt.show()

在此输入图像描述

I would say a title is more appropriate than a legend in this case. 我想说在这种情况下,标题比传奇更合适。

According to this question , the issue is ongoing, and there is a relatively simple workaround.根据这个问题,问题还在继续,有一个比较简单的解决方法。 You can manually set the two missing attributes that would allow legend to automatically create the patch for you:您可以手动设置两个缺失的属性,让legend自动为您创建补丁:

surf = ax.plot_surface(X, Y, Z, label='Lyapunov function on XY plane')
surf._edgecolors2d = surf._edgecolor3d
surf._facecolors2d = surf._facecolor3d

ax.legend()

The attribute names on the right hand side of the assignment are surf._edgecolors3d and surf.facecolors3d for matplotlib < v3.3.3.的赋值的右手侧的属性名称是surf._edgecolors3dsurf.facecolors3d为matplotlib <V3.3.3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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