我有一系列20幅图(不是子图)要在一个图中绘制。我希望图例在框外。同时,我不想改变轴,因为图形的大小会变小。
我希望图例框位于绘图区域之外(我希望图例位于绘图区域的右侧)。有没有办法减小图例框内文本的字体大小,使图例框的大小变小?
我有一系列20幅图(不是子图)要在一个图中绘制。我希望图例在框外。同时,我不想改变轴,因为图形的大小会变小。
我希望图例框位于绘图区域之外(我希望图例位于绘图区域的右侧)。有没有办法减小图例框内文本的字体大小,使图例框的大小变小?
当前回答
我只使用字符串“左中”作为位置,就像在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(loc='center left', bbox_to_anchor=(1, 0.5), fancybox = True, shadow = True)
其他回答
如前所述,您也可以将图例放置在绘图中,或稍微偏离其边缘。下面是一个使用Plotly Python API的示例,该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移动图例和图形并重新设置其样式。要移动图例,可以使用以下选项通过指定x和y值<=1来在图形中定位图例。例如:
{“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},文档中也有描述:
只需在plot()调用之后调用legend(),如下所示:
# Matplotlib
plt.plot(...)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
# Pandas
df.myCol.plot().legend(loc='center left', bbox_to_anchor=(1, 0.5))
结果如下:
简短回答:在图例上调用可拖动功能,并将其交互式移动到您想要的任何位置:
ax.legend().draggable()
长篇大论:如果您更喜欢交互式/手动放置图例,而不是以编程方式放置图例,则可以切换图例的可拖动模式,以便将其拖动到任何位置。检查以下示例:
import matplotlib.pylab as plt
import numpy as np
#define the figure and get an axes instance
fig = plt.figure()
ax = fig.add_subplot(111)
#plot the data
x = np.arange(-5, 6)
ax.plot(x, x*x, label='y = x^2')
ax.plot(x, x*x*x, label='y = x^3')
ax.legend().draggable()
plt.show()
从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()
你也可以试试figlegend。可以创建独立于任何Axes对象的图例。但是,您可能需要创建一些“虚拟”路径,以确保正确传递对象的格式。