Matplotlib:将图例转换为位图 [英] Matplotlib: Convert the legend to a bitmap

查看:85
本文介绍了Matplotlib:将图例转换为位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要图例作为单独的位图,matplotlib 可以吗?

I want the legend as a separate bitmap, is that possible with matplotlib?

import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot([1,2,3,4,5], [1,2,3,4,5], 'r')
legend = axes.legend()

如何将图例保存到位图?有什么想法吗?

How would I save legend to bitmap? Any ideas?

推荐答案

如果你想在不同的图中有一个图例,你可以使用 axes.get_legend_handles_labels() 获取图例句柄和标签并将它们添加到不同的图形中.

If you want to have a legend in a different figure, you can use axes.get_legend_handles_labels() to get the legend handles and labels and add them to a different figure.

您还需要在第一个图中提供一个图例,使用 label 参数,或明确提供与句柄关联的标签列表.

Also you need to provide a legend in the first plot, using the label argument, or to explicitly provide a list of labels to associate with the handles.

以下代码应该按照我在问题评论中的建议执行:

The following code should do what I suggested in my comment to the question:

fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot([1,2,3,4,5], [1,2,3,4,5], 'r', label='test')
legend = axes.legend()

fig2 = plt.figure()
ax = fig2.add_subplot(111)
# add the legend from a different axes
ax.legend(*axes.get_legend_handles_labels())
# hide the spines and the x/y labels
ax.axis('off')

如果您想更多地控制隐藏东西,则只能使用来隐藏轴刺

If you want more control for hiding stuff you can hide the axis spines only with

ax.set_frame_on(False)

或带有x/y标签的

ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

这篇关于Matplotlib:将图例转换为位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆