# Probability Outcomes Plot with JULIA for Fair Coin Tossing

**URL:** <https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663>\
**Category:** General Usage\
**Tags:** package, plotting\
**Created:** [February 15, 2023, 4:19am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663 "2023-02-15T04:19:00Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Freya\_the\_Goddess](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/freya_the_goddess/32/36835_2.png) [@Freya\_the\_Goddess](https://discourse.julialang.org/u/Freya_the_Goddess)\
**Post date:** [February 15, 2023, 4:19am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/1 "2023-02-15T04:19:00Z")

</div>

Hi all,

I want to plot the possible outcomes of tossing a fair coin for n times. If three times tossed then it should be like this graph:

![images](https://global.discourse-cdn.com/julialang/original/3X/a/e/ae77bf98147d90708fe661f2637938c39f65c806.png)

Which package in Julia can make this kind of graph?

---

<div class="post-metadata">

**Author:** ![hexaeder](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hexaeder/32/24403_2.png) [@hexaeder](https://discourse.julialang.org/u/hexaeder)\
**Post date:** [February 15, 2023, 5:32am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/2 "2023-02-15T05:32:54Z")

</div>

You could use [GraphMakie.jl](https://graph.makie.org/stable/generated/syntaxtree/) in the Makie or [GraphRecipes.jl](https://github.com/JuliaPlots/GraphRecipes.jl) in the Plots ecosystem.

However I think using Julia plotting libraries makes the most sense when you’re plotting data. Your example looks like you want to explain a concept with a curated graphic, for that I’d recommend to go for a tool like tikz or inkscape rather than a plotting lib.

---

<div class="post-metadata">

**Author:** ![Freya\_the\_Goddess](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/freya_the_goddess/32/36835_2.png) [@Freya\_the\_Goddess](https://discourse.julialang.org/u/Freya_the_Goddess)\
**Post date:** [February 15, 2023, 5:40am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/3 "2023-02-15T05:40:39Z")

</div>

I want to use Julia so it can calculate the probability and the outcome sets too.

Tikz is possible to graph it, but how about the numerical part? if I want to toss a coin 10 times. Julia should be able to calculate it fast with another package right?

---

<div class="post-metadata">

**Author:** ![hexaeder](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hexaeder/32/24403_2.png) [@hexaeder](https://discourse.julialang.org/u/hexaeder)\
**Post date:** [February 15, 2023, 7:10am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/4 "2023-02-15T07:10:12Z")

</div>

Yes, if you want to visualize a specific sample it makes sense to use a plotting lib. I think you can get fine results using both mentioned packages.  
In your original post the graphic includes all possible outcomes for 3 throws, without any “dynamic” data, which is why I suggested a more static approach.

---

<div class="post-metadata">

**Author:** ![gustaphe](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gustaphe/32/18174_2.png) [@gustaphe](https://discourse.julialang.org/u/gustaphe)\
**Post date:** [February 15, 2023, 7:15am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/5 "2023-02-15T07:15:00Z")

</div>

To get the probabilities, you can use the analytical expression:

```plaintext
P_k(n) = \choose{k}{n} \cdot \left(\frac{1}{2}\right)^n

```

or

```julia
probability(k, n) = nchoosek(n, k)*(1//2)^n

```

---

<div class="post-metadata">

**Author:** ![Freya\_the\_Goddess](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/freya_the_goddess/32/36835_2.png) [@Freya\_the\_Goddess](https://discourse.julialang.org/u/Freya_the_Goddess)\
**Post date:** [February 15, 2023, 9:43am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/6 "2023-02-15T09:43:47Z")

</div>

I can’t find the perfect sentences so people could understand what I want. If it is finish I will post it here.

Thanks for the reply!

---

<div class="post-metadata">

**Author:** ![empet](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/empet/32/221303_2.png) [@empet](https://discourse.julialang.org/u/empet)\
**Post date:** [February 15, 2023, 12:46pm UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/7 "2023-02-15T12:46:09Z")

</div>

I suppose that you intend to vizualize the binary tree, associated to the experiment consisting in n independent Bernoulli trials. A Bernoulli trial has two mutual exclusive outcomes: success and failure. The probability p of the succes is the same any time when you repeat the trial. In your case p=1/2. In an experiment with n independent trials one is interested in the number if successes (or failures). The random variabile X that records the number k of successes in n trials has the Binomial distribution, and P(X=k)={n \choose k} p^k (1-p)^{n-k}. In your case is given by the formula given by @gustaphe.

---

<div class="post-metadata">

**Author:** ![Freya\_the\_Goddess](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/freya_the_goddess/32/36835_2.png) [@Freya\_the\_Goddess](https://discourse.julialang.org/u/Freya_the_Goddess)\
**Post date:** [February 16, 2023, 6:42am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/8 "2023-02-16T06:42:15Z")

</div>

I have tried with an ugly graph like this:

![Capture d’écran_2023-02-16_13-40-54](https://global.discourse-cdn.com/julialang/original/3X/8/0/80a2d882c04f34befd464972a05f21a0b772b11a.png)

```julia
using GraphRecipes, Plots
gr()
default(size=(800, 400))

g = [0 1 1 0 0 0 0 0 0 0 0 0 0 0;
     0 0 0 1 1 0 0 0 0 0 0 0 0 0;
     0 0 0 0 0 1 1 0 0 0 0 0 0 0;
     0 0 0 0 0 0 0 0 0 0 0 0 0 0; 
     0 0 0 0 0 0 0 0 0 0 0 0 0 0;
     0 0 0 0 0 0 0 0 0 0 0 0 0 0;
     0 0 0 0 0 0 0 0 0 0 0 0 0 0;
     0 0 0 0 0 0 0 0 1 1 0 0 0 0;
     0 0 0 0 0 0 0 0 0 0 1 1 0 0; 
     0 0 0 0 0 0 0 0 0 0 0 0 1 1;
     0 0 0 0 0 0 0 0 0 0 0 0 0 0;
     0 0 0 0 0 0 0 0 0 0 0 0 0 0;
     0 0 0 0 0 0 0 0 0 0 0 0 0 0;
     0 0 0 0 0 0 0 0 0 0 0 0 0 0;]
graphplot(g, fontsize=12, names="H".*string.(1:14), nodeshape=:circle)

```

The problems:

1. I cannot name each node as H or T, with `H,T` won’t work
2. I really want to create like the image I post at the first post… there are seems to many Graphs packages in Julia, LightGraphs, GraphRecipes, … maybe they are more suitable to Optimization, Network Flows branches.

I might be able to use Tikz to draw the wanted image, but I think Julia should be able to do it too.

---

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [February 16, 2023, 8:48am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/9 "2023-02-16T08:48:25Z")

</div>

One possibility is to use Julia to generate the TikZ code:

```julia
using TikzPictures

function branch(result, n, i=1, prev=[])
    sofar = [prev; result]
    indent = " "^i
    distance = 5 * 2^(n-i)
    if i == n
        fullbranch = join(sofar, ",")
        prob = "\$p = \\frac{1}{$(2^n)}\$"
        return """
                $(indent)child [sibling distance=$(distance)ex]
                $(indent) { node [anchor=west] { $result \$\\cdots\$ ($fullbranch)\\; $prob } }"""
    else
        return """
                $(indent)child [sibling distance=$(distance)ex] { node {$result}
                $(branch(:T, n, i+1, sofar))
                $(branch(:H, n, i+1, sofar))
                $(indent)}"""
    end
end

function tree(n)
    return """
           \\node {}
           $(branch(:T, n))
           $(branch(:H, n));"""
end

TikzPicture(options="grow=right", tree(3))

```

![test](https://global.discourse-cdn.com/julialang/original/3X/4/d/4d703e6b305106ec99d9c6fb6de68e1c6f956913.png)

---

<div class="post-metadata">

**Author:** ![empet](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/empet/32/221303_2.png) [@empet](https://discourse.julialang.org/u/empet)\
**Post date:** [February 16, 2023, 9:08am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/10 "2023-02-16T09:08:13Z")

</div>

To define a binary tree of depth h=3, the adjacency matrix must have the size (15,15). Your matrix is (14, 14). This function creates the ajacency matrix of a perfect binary tree of depth h:

```julia
function get_adjacency(h::Int)
    nn = 2^(h+1)-1 #number of nodes
    A = zeros(Int64, nn, nn);
    j=2
    for i = 1:2^h-1
        A[i, j] = 1
        A[i, j+1] =1
        j=j+2
    end
    return A
end  

```

To assign a position to each tree node, install NetworkLayout.jl. Then with:

```julia
using Graphs, NetworkLayout
A = get_adjacency(3)
G = DiGraph(A);
node_pos = buchheim(G.fadjlist)

```

you get a binary tree placed vertically. By default, the root is at the point (0,0). To get an horizontally displayed tree, rotate the points in the vector `node_pos` around the root with an angle of π/2. The rotation matrix is [0 -1; 1;0].  
Having the new node position you can now plot the corresponding binary tree.

---

<div class="post-metadata">

**Author:** ![Freya\_the\_Goddess](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/freya_the_goddess/32/36835_2.png) [@Freya\_the\_Goddess](https://discourse.julialang.org/u/Freya_the_Goddess)\
**Post date:** [February 16, 2023, 9:15am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/11 "2023-02-16T09:15:50Z")

</div>

I didn’t know the logic behind matrix of size (15,15) for h=3, thanks @empet . I just go with my own thinking for matrix 14x14.

Julia is amazing

---

<div class="post-metadata">

**Author:** ![Freya\_the\_Goddess](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/freya_the_goddess/32/36835_2.png) [@Freya\_the\_Goddess](https://discourse.julialang.org/u/Freya_the_Goddess)\
**Post date:** [February 16, 2023, 9:17am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/12 "2023-02-16T09:17:01Z")

</div>

Wow @sijo this is what I am looking for. Thanks a bunch!

---

<div class="post-metadata">

**Author:** ![Freya\_the\_Goddess](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/freya_the_goddess/32/36835_2.png) [@Freya\_the\_Goddess](https://discourse.julialang.org/u/Freya_the_Goddess)\
**Post date:** [February 16, 2023, 9:29am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/13 "2023-02-16T09:29:28Z")

</div>

I get this when run the code at REPL:

![Capture d’écran_2023-02-16_16-28-55](https://global.discourse-cdn.com/julialang/original/3X/5/2/526957092a7b9bf6911466c700b6ddb0008d95ca.png)

why it won’t show the image?

---

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [February 16, 2023, 9:33am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/14 "2023-02-16T09:33:07Z")

</div>

The REPL cannot show images… You should see the image if you run the code in a Jupyter notebook. Or if you save the result in a variable `tp`, you can call `save(PDF("filename"), tp)` to output a PDF file (see the TikzPictures.jl documentation for more details),

(To put the image here on Discourse I used the Linux `convert` tool to convert the PDF to PNG.)

---

<div class="post-metadata">

**Author:** ![empet](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/empet/32/221303_2.png) [@empet](https://discourse.julialang.org/u/empet)\
**Post date:** [February 16, 2023, 9:35am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/15 "2023-02-16T09:35:59Z")

</div>

The adjacency matrix of a graph has the size (nn, nn), where nn is the number of nodes. Now count the nodes in the above plotted binary tree and you get 15.

---

<div class="post-metadata">

**Author:** ![Freya\_the\_Goddess](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/freya_the_goddess/32/36835_2.png) [@Freya\_the\_Goddess](https://discourse.julialang.org/u/Freya_the_Goddess)\
**Post date:** [February 16, 2023, 9:56am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/16 "2023-02-16T09:56:25Z")

</div>

I think I have to put `L """` in the right place, the pdf generated but it is empty:

```julia
using TikzPictures

function branch(result, n, i=1, prev=[])
    sofar = [prev; result]
    indent = " "^i
    distance = 5 * 2^(n-i)
    if i == n
        fullbranch = join(sofar, ",")
        prob = "\$p = \\frac{1}{$(2^n)}\$"
        return """
                $(indent)child [sibling distance=$(distance)ex]
                $(indent) { node [anchor=west] { $result \$\\cdots\$ ($fullbranch)\\; $prob } }"""
    else
        return """
                $(indent)child [sibling distance=$(distance)ex] { node {$result}
                $(branch(:T, n, i+1, sofar))
                $(branch(:H, n, i+1, sofar))
                $(indent)}"""
    end
end

function tree(n)
    return """
           \\node {}
           $(branch(:T, n))
           $(branch(:H, n));"""
end

tp = TikzPicture(L""" options="grow=right", tree(3)""")

save(PDF("test"), tp)

```

---

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [February 16, 2023, 10:01am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/17 "2023-02-16T10:01:17Z")

</div>

No you shouldn’t add any `L`: all the dollars and backslashes in my code are already escaped. So replace

```julia
tp = TikzPicture(L""" options="grow=right", tree(3)""")

```

with

```julia
tp = TikzPicture(options="grow=right", tree(3))

```

and it should work.

---

<div class="post-metadata">

**Author:** ![empet](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/empet/32/221303_2.png) [@empet](https://discourse.julialang.org/u/empet)\
**Post date:** [February 16, 2023, 11:01am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/18 "2023-02-16T11:01:41Z")

</div>

Following the steps I outlined above, I defined the binary tree associated  
to a Bernoulli experiment consisting in 4 trials. 1 encodes the trial success, while 0, the failure.  
The outcomes of this experiment are 4-length bitstrings returned by this function:

```julia
function bit_strings(h::Int)
   #returns the vector of h-length bitstrings 
   vbstr = String[]
   for i = 0:2^h-1
       s = bitstring(Int8(i)) #Int8 is sufficient for h=4, 5, 6, 7
       push!(vbstr, s[length(s)-h+1:end])    
   end
   return vbstr
end    

```

 ![Bernoulliexp](https://global.discourse-cdn.com/julialang/original/3X/d/7/d7be446449638b5c43dd1eca09b69e76796354e8.png)

---

<div class="post-metadata">

**Author:** ![Freya\_the\_Goddess](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/freya_the_goddess/32/36835_2.png) [@Freya\_the\_Goddess](https://discourse.julialang.org/u/Freya_the_Goddess)\
**Post date:** [February 16, 2023, 11:59am UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/19 "2023-02-16T11:59:58Z")

</div>

I tried with Jupyter Notebook too why this code can’t work ? Neither REPL nor notebook works.

My Julia: version 1.7.3  
status:

```julia
Status `~/LasthrimProjection/Test/Project.toml`
  [bd48cda9] GraphRecipes v0.5.12
  [86223c79] Graphs v1.8.0
  [95701278] ImplicitEquations v1.0.9
  [b964fa9f] LaTeXStrings v1.3.0
  [f0f68f2c] PlotlyJS v0.18.10
  [91a5bcdd] Plots v1.38.0
  [438e738f] PyCall v1.94.1
  [d330b81b] PyPlot v2.11.0
  [1fd47b50] QuadGK v2.6.0
  [24249f21] SymPy v1.1.7
  [37f6aa50] TikzPictures v3.4.2

```

 ![Capture d’écran_2023-02-16_17-07-55](https://global.discourse-cdn.com/julialang/original/3X/1/1/11e2bb022a08fb4d5971d31706e9afdf3926f397.png)  
 ![Capture d’écran_2023-02-16_17-05-50](https://global.discourse-cdn.com/julialang/original/3X/4/d/4d3c3d38b80c15ec33edca63551df192498d6087.png)

---

<div class="post-metadata">

**Author:** ![Freya\_the\_Goddess](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/freya_the_goddess/32/36835_2.png) [@Freya\_the\_Goddess](https://discourse.julialang.org/u/Freya_the_Goddess)\
**Post date:** [February 16, 2023, 12:00pm UTC](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663/20 "2023-02-16T12:00:54Z")

</div>

This one has a great blend of colors black and yellow!

Thanks a lot @empet .

I agree with binary results. 1 0 is the machine code anyway

[Next page](https://discourse.julialang.org/t/probability-outcomes-plot-with-julia-for-fair-coin-tossing/94663.md?page=2)
