不完全是你要求的,但我发现它是同一问题的替代方案。 让传奇半透明,如下:
这样做:
fig = pylab.figure() ax = fig.add_subplot(111) ax.plot(x,y,label=label,color=color) # Make the legend transparent: ax.legend(loc=2,fontsize=10,fancybox=True).get_frame().set_alpha(0.5) # Make a transparent text box ax.text(0.02,0.02,yourstring, verticalalignment='bottom', horizontalalignment='left', fontsize=10, bbox={'facecolor':'white', 'alpha':0.6, 'pad':10}, transform=self.ax.transAxes)
不知道你是否已经解决了你的问题...可能是的,但...... 我只是使用字符串'outside'作为位置,就像在matlab中一样。 我从matplotlib导入了pylab。 看代码如下:
from matplotlib as plt from matplotlib.font_manager import FontProperties ... ... t = A[:,0] sensors = A[:,index_lst] for i in range(sensors.shape[1]): plt.plot(t,sensors[:,i]) plt.xlabel('s') plt.ylabel('��C') lgd = plt.legend(b,loc='center left', bbox_to_anchor=(1, 0.5),fancybox = True, shadow = True)
点击查看情节
有很多方法可以做你想做的事。要添加@inalis和@Navi已经说过的内容,您可以使用 bbox_to_anchor 关键字参数,用于将图例部分放置在轴外和/或减小字体大小。
bbox_to_anchor
在考虑减小字体大小(这可能会使事情难以阅读)之前,请尝试将图例放在不同的位置:
那么,让我们从一个通用的例子开始:
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$' % i) ax.legend() plt.show()
如果我们做同样的事情,但使用 bbox_to_anchor 关键字参数我们可以稍微在轴边界外移动图例:
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$' % i) ax.legend(bbox_to_anchor=(1.1, 1.05)) plt.show()
同样,你可以使图例更加水平和/或将它放在图的顶部(我也打开圆角和一个简单的阴影):
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): line, = ax.plot(x, i * x, label='$y = %ix$'%i) ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=3, fancybox=True, shadow=True) plt.show()
或者,您可以缩小当前图的宽度,并将图例完全放在图的轴外:
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$'%i) # Shrink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Put a legend to the right of the current axis ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.show()
以类似的方式,您可以垂直缩小绘图,并将水平图例放在底部:
import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): line, = ax.plot(x, i * x, label='$y = %ix$'%i) # Shrink current axis's height by 10% on the bottom box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9]) # Put a legend below current axis ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=5) plt.show()
看看吧 matplotlib传奇指南 。你也可以看看 plt.figlegend() 。无论如何,希望有所帮助!
plt.figlegend()
如上所述,您还可以将图例放置在绘图中,或稍微偏离边缘。这是一个使用的例子 Plotly Python API 用一个 IPython笔记本 。我在团队中。
首先,您需要安装必要的软件包:
import plotly import math import random import numpy as np
然后,安装Plotly:
un='IPython.Demo' k='1fw3zw2o13' py = plotly.plotly(username=un, key=k) def sin(x,n): sine = 0 for i in range(n): sign = (-1)**i sine = sine + ((x**(2.0*i+1))/math.factorial(2*i+1))*sign return sine x = np.arange(-12,12,0.1) anno = { 'text': '$\\sum_{k=0}^{\\infty} \\frac {(-1)^k x^{1+2k}}{(1 + 2k)!}$', 'x': 0.3, 'y': 0.6,'xref': "paper", 'yref': "paper",'showarrow': False, 'font':{'size':24} } l = { 'annotations': [anno], 'title': 'Taylor series of sine', 'xaxis':{'ticks':'','linecolor':'white','showgrid':False,'zeroline':False}, 'yaxis':{'ticks':'','linecolor':'white','showgrid':False,'zeroline':False}, 'legend':{'font':{'size':16},'bordercolor':'white','bgcolor':'#fcfcfc'} } py.iplot([{'x':x, 'y':sin(x,1), 'line':{'color':'#e377c2'}, 'name':'$x\\\\$'},\ {'x':x, 'y':sin(x,2), 'line':{'color':'#7f7f7f'},'name':'$ x-\\frac{x^3}{6}$'},\ {'x':x, 'y':sin(x,3), 'line':{'color':'#bcbd22'},'name':'$ x-\\frac{x^3}{6}+\\frac{x^5}{120}$'},\ {'x':x, 'y':sin(x,4), 'line':{'color':'#17becf'},'name':'$ x-\\frac{x^5}{120}$'}], layout=l)
这将创建您的图形,并允许您有机会将图例保留在图表本身中。如果未设置,则图例的默认值是将其放置在图中,如此处所示。
对于替代放置,您可以紧密对齐图形的边缘和图例的边框,并删除边框线以便更贴合。
您可以使用代码或GUI移动和重新设置图例和图形的样式。要移动图例,可以使用以下选项通过指定< = 1的x和y值来将图例放置在图表中.E.g:
{"x" : 0,"y" : 0}
{"x" : 1, "y" : 0}
{"x" : 1, "y" : 1}
{"x" : 0, "y" : 1}
{"x" :.5, "y" : 0}
{"x": .5, "y" : 1}
在这种情况下,我们选择右上角, legendstyle = {"x" : 1, "y" : 1} ,也描述于 文件 :
legendstyle = {"x" : 1, "y" : 1}
这些方面的东西对我有用。从Joe获取的一些代码开始,此方法修改窗口宽度以自动将图例放在图的右侧。
import matplotlib.pyplot as plt import numpy as np plt.ion() x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$'%i) # Put a legend to the right of the current axis leg = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.draw() # Get the ax dimensions. box = ax.get_position() xlocs = (box.x0,box.x1) ylocs = (box.y0,box.y1) # Get the figure size in inches and the dpi. w, h = fig.get_size_inches() dpi = fig.get_dpi() # Get the legend size, calculate new window width and change the figure size. legWidth = leg.get_window_extent().width winWidthNew = w*dpi+legWidth fig.set_size_inches(winWidthNew/dpi,h) # Adjust the window size to fit the figure. mgr = plt.get_current_fig_manager() mgr.window.wm_geometry("%ix%i"%(winWidthNew,mgr.window.winfo_height())) # Rescale the ax to keep its original size. factor = w*dpi/winWidthNew x0 = xlocs[0]*factor x1 = xlocs[1]*factor width = box.width*factor ax.set_position([x0,ylocs[0],x1-x0,ylocs[1]-ylocs[0]]) plt.draw()
要将图例放置在绘图区域之外,请使用 loc 和 bbox_to_anchor 的关键词 legend() 。例如,以下代码将图例放置在绘图区域的右侧:
loc
legend()
legend(loc="upper left", bbox_to_anchor=(1,1))
有关详细信息,请参阅 传奇指南
当我有一个巨大的传奇时,对我有用的解决方案是使用额外的空图像布局。 在下面的示例中,我制作了4行,在底部我绘制了带有图例偏移的图像(bbox_to_anchor),但是它没有被剪切。
f = plt.figure() ax = f.add_subplot(414) lgd = ax.legend(loc='upper left', bbox_to_anchor=(0, 4), mode="expand", borderaxespad=0.3) ax.autoscale_view() plt.savefig(fig_name, format='svg', dpi=1200, bbox_extra_artists=(lgd,), bbox_inches='tight')
这是另一种解决方案,类似于添加 bbox_extra_artists 和 bbox_inches ,你不必将你的额外艺术家放在你的范围内 savefig 呼叫。我想出了这个,因为我在函数中生成了大部分情节。
bbox_extra_artists
bbox_inches
savefig
您可以提前将其添加到边界框中,而不是将所有添加内容添加到边界框中 Figure 的艺术家。使用类似于Franck Dernoncourt的东西 回答上面 :
Figure
import matplotlib.pyplot as plt # data all_x = [10,20,30] all_y = [[1,3], [1.5,2.9],[3,2]] # plotting function def gen_plot(x, y): fig = plt.figure(1) ax = fig.add_subplot(111) ax.plot(all_x, all_y) lgd = ax.legend( [ "Lag " + str(lag) for lag in all_x], loc="center right", bbox_to_anchor=(1.3, 0.5)) fig.artists.append(lgd) # Here's the change ax.set_title("Title") ax.set_xlabel("x label") ax.set_ylabel("y label") return fig # plotting fig = gen_plot(all_x, all_y) # No need for `bbox_extra_artists` fig.savefig("image_output.png", dpi=300, format="png", bbox_inches="tight")
这是生成的图。
你也可以试试 figlegend 。可以创建独立于任何Axes对象的图例。但是,您可能需要创建一些“虚拟”路径以确保正确传递对象的格式。
figlegend
创建字体属性
from matplotlib.font_manager import FontProperties fontP = FontProperties() fontP.set_size('small') legend([plot1], "title", prop=fontP)
以下是matplotlib教程中的一个示例 这里 。这是更简单的示例之一,但我为图例添加了透明度并添加了plt.show(),因此您可以将其粘贴到交互式shell中并获得结果:
import matplotlib.pyplot as plt p1, = plt.plot([1, 2, 3]) p2, = plt.plot([3, 2, 1]) p3, = plt.plot([2, 3, 1]) plt.legend([p2, p1, p3], ["line 1", "line 2", "line 3"]).get_frame().set_alpha(0.5) plt.show()
除了这里所有优秀的答案,更新的版本 matplotlib 和 pylab 能够 的 自动确定放置图例的位置,而不会干扰图表 强> , 如果可能的话。
matplotlib
pylab
pylab.legend(loc='best')
如果可能,这将自动将图例远离数据!
但是,如果没有地方放置图例而不重叠数据,那么您将尝试其中一个其他答案;运用 loc="best" 永远不会把传说 外 情节。
loc="best"