# PlotlyJS: Add space between legend and plot

**URL:** https://discourse.julialang.org/t/plotlyjs-add-space-between-legend-and-plot/73533
**Category:** New to Julia
**Tags:** plotting, plotlyjs
**Created:** [December 23, 2021, 3:48pm UTC](https://discourse.julialang.org/t/plotlyjs-add-space-between-legend-and-plot/73533 "2021-12-23T15:48:39Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![ellocco](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ellocco/32/31331_2.png) [@ellocco](https://discourse.julialang.org/u/ellocco)
#### Post date: [December 23, 2021, 3:48pm UTC](https://discourse.julialang.org/t/plotlyjs-add-space-between-legend-and-plot/73533/1 "2021-12-23T15:48:39Z")

</div>

It gave me really a headache to enlarge the horizontal space between my plot area and the legend.

```julia
hdl_layout = Layout(
      margin_r = 60,
)

```

does not help, it adds just space to the right.  
By changing the parameter `legend_x` I figured out, that values larger then 1.0 enlarge the gap between plot and legend. Here my example, to understand some fundamental things. I hope it is also helpful for others.

```julia
using PlotlyJS, Random, Plots
# import JSON
# ---- usefull information: ----------------------------------------------------------------------------
# https://plotly.com/julia/legend/
# -------------------------------------------------------------------------------------------------------
n_pts = 10
t_vec = collect(range( 0, length = n_pts, step = 0.1))
b_ = vec(rand(Float64, (1, n_pts)))
c_ = 1.5 .* vec(rand(Float64, (1, n_pts)))
# define empty vector of scatter handles; useful, if you would like to have variable number of scatter
hdl_scatters = Vector{GenericTrace{Dict{Symbol,Any}}}(undef, 2)

hdl_scatters[1] = scatter(; x = t_vec, y = b_, name = "Vector b")
hdl_scatters[2] = scatter(; x = t_vec, y = c_, name = "Vector c",
                  yaxis = "y2")

hdl_layout = Layout(
    title_text = "Position Legend",
    xaxis_title_text = "time / s",
    xaxis_type = "linear", # "linear" or "log" or "date" or "category" or "multicategory"
    yaxis_title_text = "1st y-axis",
    margin_r = 60, # right margin of canvas, legend is also moving
    axis_showline = false,
    legend_y = 0.5, # move up and down, vertical position
    legend_x = 1.2, # if larger 1.0 space will be added between plot area and legend
    legend_yref ="paper",
    legend_title_text = "Legend:",
    yaxis = attr(type = "log", showline = true, linewidth = 2, linecolor = "black"); # logarithmic scale
    yaxis2 = attr(
        title = "2nd y-axis",
        overlaying = "y",
        side = "right",
    )
)

hdl_plt = plot(hdl_scatters, hdl_layout)
display(hdl_plt)

if false
    FN_txt = raw"C:\data\tmp\layout.txt" # change to what make sense
    open(FN_txt, "w") do io
        write(io, JSON.json(hdl_layout.margin, 1))
    end
end

print(JSON.json(hdl_layout.margin, 1))

Plots.plotattr(:Plot, "layout")

```
