Plot a legend outside of the plotting area in base graphics?

前端 未结 10 840
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 14:48

As the title says: How can I plot a legend outside the plotting area when using base graphics?

I thought about fiddling around with layout

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 15:39

    You could do this with the Plotly R API, with either code, or from the GUI by dragging the legend where you want it.

    Here is an example. The graph and code are also here.

    x = c(0,1,2,3,4,5,6,7,8) 
    y = c(0,3,6,4,5,2,3,5,4) 
    x2 = c(0,1,2,3,4,5,6,7,8) 
    y2 = c(0,4,7,8,3,6,3,3,4)
    

    You can position the legend outside of the graph by assigning one of the x and y values to either 100 or -100.

    legendstyle = list("x"=100, "y"=1)
    layoutstyle = list(legend=legendstyle)
    

    Here are the other options:

    • list("x" = 100, "y" = 0) for Outside Right Bottom
    • list("x" = 100, "y"= 1) Outside Right Top
    • list("x" = 100, "y" = .5) Outside Right Middle
    • list("x" = 0, "y" = -100) Under Left
    • list("x" = 0.5, "y" = -100) Under Center
    • list("x" = 1, "y" = -100) Under Right

    Then the response.

    response = p$plotly(x,y,x2,y2, kwargs=list(layout=layoutstyle));

    Plotly returns a URL with your graph when you make a call. You can access that more quickly by calling browseURL(response$url) so it will open your graph in your browser for you.

    url = response$url
    filename = response$filename
    

    That gives us this graph. You can also move the legend from within the GUI and then the graph will scale accordingly. Full disclosure: I'm on the Plotly team.

    Legend on side of graph

提交回复
热议问题