1
votes

I have several functions I would like to plot on the same axis in Julia. How can I do this?

f(x) = x.^2
g(x) = 2*x
t = 1:100
# plot both f and g vs. t?

Depending on your backend, you can sometimes just plot the first function and then plot! the subsequent ones, but this doesn't work so well for the plotly backend (which has to generate a new figure for each plot). Is there a way to plot both simultaneously?

2
Note that you can also build the plot in steps. Start with p = plot(t, f), then plot!(p, t, g), then printing p should show the entire plot. - Timothée Poisot

2 Answers

7
votes

Call plot on a vector of all the things you would like plotted together:

plot(t,[f,g])

This also works with combinations of e.g. functions and vectors:

plot(t,[f,g,t.^2])
1
votes

For a Jupyter Notebook with Julia v0.6

I prefer to use pure PlotlyJS instead of going through Plots.jl. Here's a simple example on how to plot two curves on the same axis.

using PlotlyJS

X = -5:0.01:5
Y1 = e.^(X)
Y2 = e.^(-X)

trace1 = PlotlyJS.scatter(;x=X, y=Y1, mode="lines", line_color="blue", name="e^x")
trace2 = PlotlyJS.scatter(;x=X, y=Y2, mode="lines", line_color="red", name="e^(-x)")
layout = PlotlyJS.Layout(xaxis_range=[-5, 5], yaxis_range=[0, 10])

PlotlyJS.plot([trace1, trace2], layout)

If you wanted to plot two axes side-by-side (each with multiple curves), you can do this

p1 = PlotlyJS.plot([trace1, trace2], layout)
p2 = PlotlyJS.plot([trace1, trace2], layout)

# Show the plots next to each other
[p1 p2]