Bebotron
Bebotron

Reputation: 443

hline/vline with subplots in Julia

I'm trying to add a horizontal line to a subplot, and from this discussion: https://discourse.julialang.org/t/vline-with-subplots/25479/2, I have the following

x = [1,2,3]
y1 = 2x
y2 = x.^2
plot([x, x], [y1, y2], layout = (2, 1))
hline!([4 4])

Which produces the plots.

plots

Now what I'm trying to do is do the horizontal line on the bottom plot, but not the top one. If I just specify hline!([4]) , it defaults to the top one. Is there a way to do the bottom one only?

Upvotes: 3

Views: 5765

Answers (2)

Benoit Pasquier
Benoit Pasquier

Reputation: 3015

It's probably best practice to plot subplots separately (as mentioned on Slack by isentropic):

x = [1,2,3]
y1 = 2x
y2 = x.^2
p1 = plot(x, y1)
p2 = plot(x, y2)
hline!(p2, [4])
plot(p1, p2, layout = (2, 1))

But if you want it all in one go, you could have used

hline!([[NaN], [4]])

Upvotes: 2

cbk
cbk

Reputation: 4370

The trick is to keep track of the plot handles.

p = plot([x, x], [y1, y2], layout = (2, 1))

returns a plot handle (specifically, a Plots.Plot{Plots.GRBackend} object) p with two elements, p[1] (the first subplot) and p[2] (the second subplot). To add the hline to the bottom plot only, then, you can write:

x = [1,2,3]
y1 = 2x
y2 = x.^2
p = plot([x, x], [y1, y2], layout = (2, 1))
hline!(p[2], [4])

enter image description here

Upvotes: 4

Related Questions