Dila
Dila

Reputation: 689

Plotting two distributions on same plot

I am trying to plot two probability distributions onto the same plot. One is a uniform distribution with area under the curve = 1 and the other is a chi distribution (or to be more specific, a Maxwellian) with three degrees of freedom with area under the curve = 1. Here is my code so far:

using Plots, Distributions
gr()

v = -0.5:0.001:1.5
f_s0 = pdf.(Uniform(0,1), v) # uniform distribution with area 1
F_s = pdf.(Chi(3), v)  # chi distribution with area 1

plot(v, f_s0, label="f_s0")
plot!(v, F_s, linecolor = :orange, linestyle = :dash, label="F_s (Maxwellian)")
xlabel!("velocity")
ylabel!("probability density")
xlims!(-0.5, 1.5)
ylims!(0, 1.5)

When I run this, I get

DomainError with -0.5:
log will only return a complex result if called with a complex argument. Try log(Complex(x)).

Any suggestions?

Upvotes: 3

Views: 821

Answers (3)

cbk
cbk

Reputation: 4370

The Chi distribution is only defined on the nonnegative numbers, and this is really a constraint of math rather than programming. If you are considering a Chi distribution, this may suggest that the quantity you are considering cannot even be negative, in which case the answer is to only plot for positive x values anyways. Nonetheless, if you want to show the Uniform distribution going back to zero, then I would do something like the following.

using Plots, Distributions

vᵤ = -0.1:0.005:4
f_s0 = pdf.(Uniform(0,1), vᵤ) # uniform distribution with area 1
plot(vᵤ, f_s0, label="f_s0", framestyle=:box)

vᵪ = 0:0.005:4
F_s = pdf.(Chi(3), vᵪ)  # chi distribution with area 1

plot!(vᵪ, F_s, linecolor = :orange, linestyle = :dash, label="F_s (Maxwellian)")
xlabel!("velocity")
ylabel!("probability density")
xlims!(-0.1, 4)
ylims!(0, 1.5)

yielding Uniform and Chi distributions

Upvotes: 0

barpapapa
barpapapa

Reputation: 153

Probably there is a issue with Distributions, you can define a function as a workaround:

using Plots, Distributions
gr()

v = -0.5:0.001:1.5
f_s0 = pdf.(Uniform(0,1), v) # uniform distribution with area 1

CHIPDF(x) = x>0 ? pdf(Chi(3),x) : 0

F_s = CHIPDF.(v)  # chi distribution with area 1

plot(v, f_s0, label="f_s0")
plot!(v, F_s, linecolor = :orange, linestyle = :dash, label="F_s (Maxwellian)")
xlabel!("velocity")
ylabel!("probability density")
xlims!(-0.5, 1.5)
ylims!(0, 1.5)

Upvotes: 1

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

Chi distribution starts from zero so this should be:

F_s = pdf.(Chi(3), 0:0.001:1.5)

Upvotes: 2

Related Questions