简体   繁体   English

如何将图例添加到 Mayavi 图中

[英]How can I add a legend to a mayavi plot

I can't seem to get a legend to appear on a mayavi plot.我似乎无法让传说出现在 Mayavi 情节中。 I have created a simple 3d plot but I need to provide a legend for the plot.我创建了一个简单的 3d 图,但我需要为该图提供一个图例。 Matplotlib supports adding by: Matplotlib 支持添加:

import matplotlib.pyplot as plt
plt.plot(x, y, z, label="my-label")

I didn't find any working examples of such legends in mayavi.我在 mayavi 中没有找到此类传说的任何工作示例。

Since mayavi doesn't have a built in method for creating legends the easiest way to do this would be to create your mavavi figure and then read it into matplotlib and make a legend.由于 mayavi 没有用于创建图例的内置方法,因此最简单的方法是创建您的 mavavi 图,然后将其读入 matplotlib 并制作图例。 This requires you to have programmatic access to the color values used in creating the mayavi plot - it is much easier when you specify the colors explicitly instead of letting the color cycler automatically assign colors.这要求您以编程方式访问用于创建 mayavi 绘图的颜色值 - 当您明确指定颜色而不是让颜色循环器自动分配颜色时,会容易得多。

Here is an example which creates a mayavi figure and then passes it to matplotlib to then create a legend.这是一个创建 mayavi 图形然后将其传递给 matplotlib 以创建图例的示例。

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import mayavi.mlab as mlab
from mayavi.api import OffScreenEngine
import numpy as np

mlab.options.offscreen = True
e = OffScreenEngine()
e.start()
fig = mlab.figure(engine=e, size=(5000,5000), fgcolor=(0,0,0), bgcolor=(1,1,1))
mlab.view(azimuth=45, elevation=0)

n = 500
d = np.linspace(0, np.pi*8, n)

mlab.plot3d(d, np.cos(d**1.2), np.cos(d), color = colors[0])
mlab.plot3d(d, np.sin(d), np.sin(d), color = colors[1])
mlab.plot3d(d, np.sin(d)*np.cos(d), np.cos(d), color = colors[2])
mlab.plot3d(d, np.sin(d)**2, np.sin(d)**2, color = colors[3])

mlab.savefig("./example.png")

im = plt.imread("./example.png")
labels = ["One", "Two", "Three", "Four"]

elements = [Line2D([0], [0], label = l, color = c) for l, c in zip(labels, colors[:4])]
plt.imshow(im)
plt.legend(handles = elements)
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, 
            hspace = 0, wspace = 0)
plt.margins(0,0)
plt.savefig("./example.png")

colors is an array of RGB values in the range [0.0, 1.0] . colors[0.0, 1.0]范围内的RGB值数组。 The example uses the Tableau 20 color palette mapped into the [0.0, 1.0] space.该示例使用映射到[0.0, 1.0]空间的Tableau 20 调色板 This generates the following output这将生成以下输出

在此处输入图片说明

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

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