Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move the legend to outside the plotting area in Plots.jl (GR)?

Tags:

julia

plots.jl

I have the following plot where part of the data is being obscured by the legend:

using Plots; gr()
using StatPlots
groupedbar(rand(1:100,(10,10)),bar_position=:stack, label="item".*map(string,collect(1:10)))

stacked bar plot

I can see that using the "legend" attribute, the legend can be moved to various locations within the plotting area, for example:

groupedbar(rand(1:100,(10,10)),bar_position=:stack, label="item".*map(string,collect(1:10)),legend=:bottomright)

stacked bar plot with legend at bottom right

Is there any way of moving the plot legend completely outside the plotting area, for example to the right of the plot or below it? For these kinds of stacked bar plots there's really no good place for the legend inside the plot area. The only solution I've been able to come up with so far is to make some "fake" empty rows in the input data matrix to make space with some zeros, but that seems kind of hacky and will require some fiddling to get the right number of extra rows each time the plot is made:

groupedbar(vcat(rand(1:100,(10,10)),zeros(3,10)),bar_position=:stack, label="item".*map(string,collect(1:10)),legend=:bottomright)

stacked bar plot with legend placed in extra white space

I can see that at there was some kind of a solution proposed for pyplot, does anyone know of a similar solution for the GR backend? Another solution I could imagine - is there a way to save the legend itself to a different file so I can then put them back together in Inkscape?

like image 423
Ian Marshall Avatar asked Jul 14 '17 07:07

Ian Marshall


People also ask

How do I move the legend outside the plot in R?

In order to draw our legend outside of the plotting area, we can use a combination of the “topright” argument and an additional specification of inset. The “topright” argument specifies that the legend should be in the upper right corner of the graph.

How do you save the story of Julia?

Julia – Save Plot as PNG or JPEG To save a plot to local file storage, use the method savefig("filename") or png("filename") .


2 Answers

This is now easily enabled with Plots.jl:

Example:

plot(rand(10), legend = :outertopleft)

enter image description here

like image 87
Alec Avatar answered Oct 01 '22 19:10

Alec


Using layouts I can create a workaround making a fake plot with legend only.

using Plots
gr()
l = @layout [a{0.001h}; b c{0.13w}]

values = rand(1:100,(10,10))

p1 = groupedbar(values,bar_position=:stack, legend=:none)
p2 = groupedbar(values,bar_position=:stack, label="item".*map(string,collect(1:10)), grid=false, xlims=(20,3), showaxis=false)


p0=plot(title="Title",grid=false, showaxis=false)

plot(p0,p1,p2,layout=l)

enter image description here

like image 33
Thuener Avatar answered Oct 01 '22 17:10

Thuener