Python 如何将传奇故事排除在情节之外

Python 如何将传奇故事排除在情节之外,python,matplotlib,legend,Python,Matplotlib,Legend,我有一系列的20个图(不是子图)要在一个图形中绘制。我希望图例在盒子外面。同时,我不想更改轴,因为图形的大小会减小。请帮我解答以下问题: 我希望将图例框保留在绘图区域之外。(我希望图例位于绘图区域右侧的外侧) 无论如何,我是否要减小图例框内文本的字体大小,使图例框的大小变小 您可以通过指定FontProperties的set\u size使图例文本变小 资源: 有效字体大小为xx小、x小、小、中、大、x大、xx大、大、小、无 导入matplotlib.pyplot作为

我有一系列的20个图(不是子图)要在一个图形中绘制。我希望图例在盒子外面。同时,我不想更改轴,因为图形的大小会减小。请帮我解答以下问题:

  • 我希望将图例框保留在绘图区域之外。(我希望图例位于绘图区域右侧的外侧)
  • 无论如何,我是否要减小图例框内文本的字体大小,使图例框的大小变小
    • 您可以通过指定
      FontProperties
      set\u size
      使图例文本变小
    • 资源:
        • 有效字体大小为xx小、x小、小、中、大、x大、xx大、大、小、无
    导入matplotlib.pyplot作为plt
    从matplotlib.font_管理器导入FontProperties
    fontP=FontProperties()
    fontP.set_大小('xx-small')
    p1,=plt.plot([1,2,3],label='Line 1')
    p2,=plt.plot([3,2,1],label='Line 2')
    plt.图例(手柄=[p1,p2],title='title',bbox_to_锚=(1.05,1),loc='左上角',prop=fontP)
    

    • 如所述,
      fontsize='xx-small'
      也可以工作,无需导入
      FontProperties
    plt.legend(句柄=[p1,p2],title='title',bbox_to_锚=(1.05,1),loc='左上角',fontsize='xx-small')
    
    要将图例放置在绘图区域之外,请使用
    loc
    bbox\u锚定
    图例()的关键字。例如,以下代码将图例放置在绘图区域的右侧:

    legend(loc="upper left", bbox_to_anchor=(1,1))
    

    有关更多信息,请参见

    有多种方法可以实现您的愿望。要添加@inalis和@Navi已经说过的内容,可以使用
    bbox\u To\u 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\u to\u 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()
    

    类似地,使图例更水平,并/或将其放置在图形顶部(我还将打开圆角和简单的阴影):

    或者,缩小当前绘图的宽度,并将图例完全放在图形的轴之外(注意:如果使用,则省略
    ax.set_position()

    以类似的方式,垂直收缩绘图,并在底部放置一个水平图例:

    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()
    


    查看。您也可以查看。

    您也可以尝试
    figlegend
    。可以创建独立于任何轴对象的图例。但是,您可能需要创建一些“虚拟”确保正确传递对象格式的路径。

    简短回答:在图例上调用Dragable,并以交互方式将其移动到任何需要的位置:

    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()
    

    如前所述,您也可以将图例放置在绘图中,或稍微偏离其边缘。下面是一个使用的示例,由一个。我是团队成员

    首先,您需要安装必要的软件包:

    import plotly
    import math
    import random
    import numpy as np
    
    然后,以绘图方式安装:

    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值将图例放置在图形中,这与您的要求不符,但我发现这是解决同一问题的另一种方法。 使图例半透明,如下所示:

    通过以下方式执行此操作:

    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)
    

    下面是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()
    
    只需在
    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))
    
    结果如下所示:

    # 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))
    

    简短回答:你可以使用
    bbox\u来锚定
    +
    bbox\u额外的艺术家
    +
    bbox\u inches='tight'


    详细回答: 您可以使用
    bbox\u to\u anchor
    手动指定图例框的位置,正如其他人在回答中指出的那样

    但是,通常的问题是图例框被裁剪,例如:

    import matplotlib.pyplot as plt
    
    # data 
    all_x = [10,20,30]
    all_y = [[1,3], [1.5,2.9],[3,2]]
    
    # Plot
    fig = plt.figure(1)
    ax = fig.add_subplot(111)
    ax.plot(all_x, all_y)
    
    # Add legend, title and axis labels
    lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
    ax.set_title('Title')
    ax.set_xlabel('x label')
    ax.set_ylabel('y label')
    
    fig.savefig('image_output.png', dpi=300, format='png')
    

    为了防止图例框被裁剪,在保存图形时,可以使用参数
    bbox\u extra\u artists
    bbox\u inches
    要求
    savefig
    在保存的图像中包含裁剪的元素:

    fig.savefig('image\u output.png',bbox\u extra\u美工=(lgd,),bbox\u inches='tight')

    示例(我只更改了最后一行,将两个参数添加到
    fig.savefig()
    ):

    我希望matplotlib本机允许图例框的外部位置为:


    除了所有的例外
    import matplotlib.pyplot as plt
    
    # data 
    all_x = [10,20,30]
    all_y = [[1,3], [1.5,2.9],[3,2]]
    
    # Plot
    fig = plt.figure(1)
    ax = fig.add_subplot(111)
    ax.plot(all_x, all_y)
    
    # Add legend, title and axis labels
    lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
    ax.set_title('Title')
    ax.set_xlabel('x label')
    ax.set_ylabel('y label')
    
    fig.savefig('image_output.png', dpi=300, format='png')
    
    import matplotlib.pyplot as plt
    
    # data 
    all_x = [10,20,30]
    all_y = [[1,3], [1.5,2.9],[3,2]]
    
    # Plot
    fig = plt.figure(1)
    ax = fig.add_subplot(111)
    ax.plot(all_x, all_y)
    
    # Add legend, title and axis labels
    lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
    ax.set_title('Title')
    ax.set_xlabel('x label')
    ax.set_ylabel('y label')    
    
    fig.savefig('image_output.png', dpi=300, format='png', bbox_extra_artists=(lgd,), bbox_inches='tight')
    
    figure
    x = 0:.2:12;
    plot(x,besselj(1,x),x,besselj(2,x),x,besselj(3,x));
    hleg = legend('First','Second','Third',...
                  'Location','NorthEastOutside')
    % Make the text of the legend italic and color it brown
    set(hleg,'FontAngle','italic','TextColor',[.3,.2,.1])
    
    pylab.legend(loc='best')
    
    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')
    
    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)
    
    plt.legend(loc=(1.04,0))
    
    plt.legend(bbox_to_anchor=(1.04,1), loc="upper left")
    l1 = plt.legend(bbox_to_anchor=(1.04,1), borderaxespad=0)
    l2 = plt.legend(bbox_to_anchor=(1.04,0), loc="lower left", borderaxespad=0)
    l3 = plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)
    l4 = plt.legend(bbox_to_anchor=(0,1.02,1,0.2), loc="lower left",
                    mode="expand", borderaxespad=0, ncol=3)
    l5 = plt.legend(bbox_to_anchor=(1,0), loc="lower right", 
                    bbox_transform=fig.transFigure, ncol=3)
    l6 = plt.legend(bbox_to_anchor=(0.4,0.8), loc="upper right")
    
      plt.subplots_adjust(right=0.7)
    
      plt.tight_layout(rect=[0,0,0.75,1])
    
      plt.savefig("output.png", bbox_inches="tight")
    
    fig.legend(loc=7) 
    
    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(0,2*np.pi)
    colors=["#7aa0c4","#ca82e1" ,"#8bcd50","#e18882"]
    fig, axes = plt.subplots(ncols=2)
    for i in range(4):
        axes[i//2].plot(x,np.sin(x+i), color=colors[i],label="y=sin(x+{})".format(i))
    
    fig.legend(loc=7)
    fig.tight_layout()
    fig.subplots_adjust(right=0.75)   
    plt.show()
    
    import matplotlib.pyplot as plt
    plt.rcParams["figure.figsize"] = 6,2
    
    fig, (ax,lax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios":[4,1]})
    ax.plot(x,y, label="y=sin(x)")
    ....
    
    h,l = ax.get_legend_handles_labels()
    lax.legend(h,l, borderaxespad=0)
    lax.axis("off")
    
    plt.tight_layout()
    plt.show()
    
    ax.legend(bbox_to_anchor=(0,0,1,1), bbox_transform=lax.transAxes)
    lax.axis("off")
    
    import matplotlib.pyplot as plt
    
    plt.plot([0, 1], [0, 1], label="Label 1")
    plt.plot([0, 1], [0, 2], label='Label 2')
    
    plt.legend(loc=(1.05, 0.5))
    plt.tight_layout()