gTcV
gTcV

Reputation: 2504

Increase space between subplots in Plots.jl

How can I increase the space between subplots in Plots.jl?

Minimal non-working example:

julia> using Plots; pyplot()
Plots.PyPlotBackend()

julia> data = [rand(100), rand(100)];
       histogram(data, layout=2, title=["Dataset A" "Dataset B"], legend=false)
       ylabel!("ylabel")

If you make the figure small enough, the y label of the second plot collides with the first plot.

Upvotes: 6

Views: 7778

Answers (3)

ya wei
ya wei

Reputation: 127

An alternative is to use the empty figure object _ to occupy the space. It works well when a long legend name overlaps with another subplot with PGFPlotsX backend,

pgfplotsx()
p1 = plot(1:10, label = "a long label name")
p2 = plot(1:10)
plot(p1, p2)

enter image description here

we can use _ in @layout to leave more space for the legend of the first subplot,

plot(p1, p2, layout=@layout([a{0.5w} _ b{0.3w}]))

enter image description here

It can even handle more complicated cases. For example, you might just want to increase the space between two specific subplots instead of all subplots. For example, I use the setting

layout = @layout([grid(2, 1){0.3w} _ grid(2, 1){0.3w} b{0.33w}])

to leave more space via _ for the legend for the left two subplots grid(2,1), but do not touch other subplots.

Upvotes: 1

Shayan
Shayan

Reputation: 6285

Another workaround would be using the bottom_margin keyword argument holding the pyplot backend like this:

using Plots
pyplot()

x1 = rand(1:30, 20);
x2 = rand(1:30, 20);

# subplot 1
p1 = plot(
    x1,
    label="x1 value",
    title="x1 line plot",
    ylabel="x1",
    bottom_margin=50*Plots.mm,
);

# subplot 2
p2 = plot(
    x2,
    label="x2 value",
    title="x2 line plot",
    xlabel="sample",
    ylabel="x2",
);

plot(
    p1,
    p2,
    layout=grid(
        2,1,
    )
)

enter image description here

Upvotes: 2

Arda Aytekin
Arda Aytekin

Reputation: 1301

In the attributes part of Plots.jl documentation, there is a section called Subplot. There, you will find the keywords margin, top_margin, bottom_margin, left_margin and right_margin that might help you.

Minimal working example would be, then:

using Plots, Measures
pyplot()

data = [rand(100), rand(100)];

histogram(data, layout = 2,
          title = ["Dataset A" "Dataset B"], legend = false,
          ylabel = "ylabel", margin = 5mm)

Note the using Measures part, by the way. I hope this helps.

Upvotes: 10

Related Questions