How to put the legend out of the plot

后端 未结 17 3155
时光说笑
时光说笑 2020-11-21 04:42

I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, a

17条回答
  •  温柔的废话
    2020-11-21 05:24

    As noted, you could also place the legend in the plot, or slightly off it to the edge as well. Here is an example using the Plotly Python API, made with an IPython Notebook. I'm on the team.

    To begin, you'll want to install the necessary packages:

    import plotly
    import math
    import random
    import numpy as np
    

    Then, install 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)
    

    This creates your graph, and allows you a chance to keep the legend within the plot itself. The default for the legend if it is not set is to place it in the plot, as shown here.

    enter image description here

    For an alternative placement, you can closely align the edge of the graph and border of the legend, and remove border lines for a closer fit.

    enter image description here

    You can move and re-style the legend and graph with code, or with the GUI. To shift the legend, you have the following options to position the legend inside the graph by assigning x and y values of <= 1. E.g :

    • {"x" : 0,"y" : 0} -- Bottom Left
    • {"x" : 1, "y" : 0} -- Bottom Right
    • {"x" : 1, "y" : 1} -- Top Right
    • {"x" : 0, "y" : 1} -- Top Left
    • {"x" :.5, "y" : 0} -- Bottom Center
    • {"x": .5, "y" : 1} -- Top Center

    In this case, we choose the upper right, legendstyle = {"x" : 1, "y" : 1}, also described in the documentation:

    enter image description here

提交回复
热议问题