首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将matplotlib图例移动到轴外将使其被图形框截断

将matplotlib图例移动到轴外将使其被图形框截断
EN

Stack Overflow用户
提问于 2012-04-11 15:32:09
回答 3查看 194.3K关注 0票数 259

我熟悉以下问题:

Matplotlib savefig with a legend outside the plot

How to put the legend out of the plot

似乎这些问题中的答案都可以随意调整轴的精确收缩,以便与图例相吻合。

然而,缩小轴并不是一个理想的解决方案,因为它会使数据变得更小,实际上更难解释;特别是当它很复杂,有很多事情在发生时……因此需要一个大的图例

文档中复杂图例的示例演示了这种需要,因为它们图中的图例实际上完全遮挡了多个数据点。

http://matplotlib.sourceforge.net/users/legend_guide.html#legend-of-complex-plots

我想要做的是动态扩展数字框的大小,以适应不断扩展的数字图例。

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))
ax.grid('on')

注意最后的标签“反转黄褐色”实际上在图框外(而且看起来很糟糕--不是出版质量!)

最后,我被告知这是R和LaTeX中的正常行为,所以我有点困惑为什么这在python中这么难……有没有历史原因?在这个问题上,Matlab也同样糟糕吗?

我在pastebin http://pastebin.com/grVjc007上有这个代码的(只有一点点)更长的版本

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-04-14 23:26:21

抱歉,EMS,但实际上我刚刚从matplotlib邮件列表中得到了另一个回复(感谢本杰明·鲁特)。

我正在寻找的代码是将savefig调用调整为:

fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable

这显然类似于调用tight_layout,但是您允许savefig在计算中考虑额外的艺术家。这实际上根据需要调整了数字框的大小。

import matplotlib.pyplot as plt
import numpy as np

plt.gcf().clear()
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')

这会产生以下结果:

编辑这个问题的目的是完全避免使用任意文本的任意坐标位置,因为这是这些问题的传统解决方案。尽管如此,最近的许多编辑都坚持将它们放入其中,通常是以导致代码引发错误的方式。现在,我已经修复了这些问题,并整理了任意文本,以显示如何在bbox_extra_artists算法中考虑这些问题。

票数 348
EN

Stack Overflow用户

发布于 2012-04-13 14:42:13

补充道:我发现了一些可以立即解决问题的方法,但下面的其余代码也提供了另一种选择。

使用subplots_adjust()函数向上移动子图的底部:

fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot.

然后使用图例命令的图例bbox_to_anchor部分中的偏移量,将图例框放在您想要的位置。设置figsize和使用subplots_adjust(bottom=...)的某种组合应该会为您生成高质量的绘图。

Alternative:我只是简单地更改了这一行:

fig = plt.figure(1)

至:

fig = plt.figure(num=1, figsize=(13, 13), dpi=80, facecolor='w', edgecolor='k')

并且改变了

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,-0.02))

它在我的屏幕(24英寸的CRT显示器)上显示得很好。

在这里,figsize=(M,N)将图形窗口设置为M英寸x N英寸。试着使用它,直到它看起来适合你。将其转换为更具可伸缩性的图像格式,并在必要时使用GIMP进行编辑,或者在包含图形时仅使用LaTeX viewport选项进行裁剪。

票数 32
EN

Stack Overflow用户

发布于 2013-04-08 15:06:31

这是另一个非常手动的解决方案。您可以定义轴的大小,并相应地考虑填充(包括图例和记号)。希望对某些人有用。

示例(轴大小相同!):

代码:

#==================================================
# Plot table

colmap = [(0,0,1) #blue
         ,(1,0,0) #red
         ,(0,1,0) #green
         ,(1,1,0) #yellow
         ,(1,0,1) #magenta
         ,(1,0.5,0.5) #pink
         ,(0.5,0.5,0.5) #gray
         ,(0.5,0,0) #brown
         ,(1,0.5,0) #orange
         ]


import matplotlib.pyplot as plt
import numpy as np

import collections
df = collections.OrderedDict()
df['labels']        = ['GWP100a\n[kgCO2eq]\n\nasedf\nasdf\nadfs','human\n[pts]','ressource\n[pts]'] 
df['all-petroleum long name'] = [3,5,2]
df['all-electric']  = [5.5, 1, 3]
df['HEV']           = [3.5, 2, 1]
df['PHEV']          = [3.5, 2, 1]

numLabels = len(df.values()[0])
numItems = len(df)-1
posX = np.arange(numLabels)+1
width = 1.0/(numItems+1)

fig = plt.figure(figsize=(2,2))
ax = fig.add_subplot(111)
for iiItem in range(1,numItems+1):
  ax.bar(posX+(iiItem-1)*width, df.values()[iiItem], width, color=colmap[iiItem-1], label=df.keys()[iiItem])
ax.set(xticks=posX+width*(0.5*numItems), xticklabels=df['labels'])

#--------------------------------------------------
# Change padding and margins, insert legend

fig.tight_layout() #tight margins
leg = ax.legend(loc='upper left', bbox_to_anchor=(1.02, 1), borderaxespad=0)
plt.draw() #to know size of legend

padLeft   = ax.get_position().x0 * fig.get_size_inches()[0]
padBottom = ax.get_position().y0 * fig.get_size_inches()[1]
padTop    = ( 1 - ax.get_position().y0 - ax.get_position().height ) * fig.get_size_inches()[1]
padRight  = ( 1 - ax.get_position().x0 - ax.get_position().width ) * fig.get_size_inches()[0]
dpi       = fig.get_dpi()
padLegend = ax.get_legend().get_frame().get_width() / dpi 

widthAx = 3 #inches
heightAx = 3 #inches
widthTot = widthAx+padLeft+padRight+padLegend
heightTot = heightAx+padTop+padBottom

# resize ipython window (optional)
posScreenX = 1366/2-10 #pixel
posScreenY = 0 #pixel
canvasPadding = 6 #pixel
canvasBottom = 40 #pixel
ipythonWindowSize = '{0}x{1}+{2}+{3}'.format(int(round(widthTot*dpi))+2*canvasPadding
                                            ,int(round(heightTot*dpi))+2*canvasPadding+canvasBottom
                                            ,posScreenX,posScreenY)
fig.canvas._tkcanvas.master.geometry(ipythonWindowSize) 
plt.draw() #to resize ipython window. Has to be done BEFORE figure resizing!

# set figure size and ax position
fig.set_size_inches(widthTot,heightTot)
ax.set_position([padLeft/widthTot, padBottom/heightTot, widthAx/widthTot, heightAx/heightTot])
plt.draw()
plt.show()
#--------------------------------------------------
#==================================================
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10101700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档