[Question]
  [
# The Collatz sequence
Given a positive integer \$a\_1\$, the [Collatz sequence](https://en.wikipedia.org/wiki/Collatz_conjecture) with starting value \$a\_1\$ is defined as
\begin{equation}
a\_{n+1} =
\begin{cases}
a\_n/2 & \mathrm{if}\ a\_n\ \mathrm{is}\ \mathrm{even} \\
3a\_n+1 & \mathrm{if}\ a\_n\ \mathrm{is}\ \mathrm{odd}.
\end{cases}
\end{equation}
It is [conjectured](https://en.wikipedia.org/wiki/Collatz_conjecture#Statement_of_the_problem) that, for any starting value, this sequence always reaches the number \$1\$. This challenge assumes that the conjecture is true.
# The challenge
Given an integer \$a\_1 > 2\$, compute the Collatz sequence until \$1\$ is reached for the first time. Let \$N\$ be the number of sequence terms (including \$a\_1\$ and \$a\_N = 1\$). From the sequence of numbers
\begin{equation}
a\_1, a\_2, a\_3, \ldots, a\_N
\end{equation}
form a sequence of points in the plane by taking all pairs of consecutive terms
\begin{equation}
(a\_1, a\_2), (a\_2, a\_3), \ldots, (a\_{N-1}, a\_N)
\end{equation}
and plot these points on a 2D graph, joining consecutive points by a line segment.
# Example
For input \$12\$ the Collatz sequence is (\$10\$ terms);
\begin{equation}
12, 6, 3, 10, 5, 16, 8, 4, 2, 1.
\end{equation}
The sequence of points is (\$9\$ points):
\begin{equation}
(12, 6), (6, 3), (3, 10), (10, 5), (5, 16), (16, 8), (8, 4), (4, 2), (2, 1).
\end{equation}
The plot contains \$8\$ line segments, as shown in the following graph. Note that some of the segments partially overlap. For clarity, the plot includes markers at the \$9\$ points.
[![enter image description here](https://i.stack.imgur.com/SXS7n.png)](https://i.stack.imgur.com/SXS7n.png)
# Additional rules
* Graphical output is required, with output being [flexible](https://codegolf.meta.stackexchange.com/questions/9093/default-acceptable-image-i-o-methods-for-image-related-challenges) as usual.
* Only the straight lines are required in the graph. Line width is flexible, as long as the plot can be seen reasonably well. Line color is also flexible, and may be different for each segment, as long as lines are distinguishable from the background.
* Other elements in the graph are not required, but are allowed (point markers, grid lines, axis labels, ...).
* Horizontal and vertical axis scales need not be the same. Axis limits are arbitrary, as long as the graph can be seen fully and clearly. The axes may be swapped, and each axis may be reversed.
* The code should work for any input given unlimited resources. It is acceptable if in practice it fails for large inputs due to time, memory or data-type limitations.
* If the input happens to be a counterexample for the Collatz conjecture the code can do anything, such as get stuck in an infinite loop or order a pizza.
* [Programs or functions](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet) are accepted. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Shortest code in bytes wins.
# Test cases
| Input | Output |
| --- | --- |
| `3` | [enter image description here](https://i.stack.imgur.com/u8p5i.png) |
| `4` | [enter image description here](https://i.stack.imgur.com/4DtDx.png) |
| `27` | [enter image description here](https://i.stack.imgur.com/xOUsN.png) |
| `649` | [enter image description here](https://i.stack.imgur.com/Mt3Fs.png) |
| `650` | [enter image description here](https://i.stack.imgur.com/5eSka.png) |
| `46720` | [enter image description here](https://i.stack.imgur.com/rL0ly.png) |
| `345435` | [enter image description here](https://i.stack.imgur.com/LUtDC.png) |
| `63728127` | [enter image description here](https://i.stack.imgur.com/xTgng.png) |
 
  
[Answer]
# [Python 3.8](https://docs.python.org/3.8/) with turtle, ~~156~~ 127 bytes
Thanks to [Noodle9](https://codegolf.stackexchange.com/users/9481/noodle9) for catching a mistake!
```
from turtle import*
def f(n,x=0):
 while~-n:goto(w:=n,n:=[n//2,3*n+1][n%2]);x<1!=clear();setworldcoordinates(0,0,x:=max(x,n),x)
```
Animation for \$a\_1=27\$:
[![animation of turtle for testcase 27](https://i.stack.imgur.com/1dSRs.gif)](https://i.stack.imgur.com/1dSRs.gif)
[Answer]
# [J](http://jsoftware.com/), 52 bytes
```
load 'plot'
f=:[:plot[:(}:;}.)(2&|{-:,1+*&3)^:(>&1)^:a:
```
[Try it online!](https://tio.run/##y/r/Pyc/MUVBvSAnv0SdK83WKtoKxIy20qi1sq7V09QwUqup1rXSMdTWUjPWjLPSsFMzBFKJVv//AwA "J – Try It Online")
Wasn't sure if loading the graphics lib counted towards byte count, so I included it.
Here's an image of calling `f 27` in the J console:
[![27](https://i.stack.imgur.com/UG8UB.png)](https://i.stack.imgur.com/UG8UB.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes
```
r0×€:⁸
×3‘ƊHḂ?Ƭ;Ɲ_/AÞṪçƊ+ṪƲƝẎŒṬx€€3
```
[Try it online!](https://tio.run/##y0rNyan8/7/I4PD0R01rrB417uA6PN34UcOMY10eD3c02R9bY31sbry@4@F5D3euOrz8WJc2kD626djch7v6jk56uHNNBVAbEBn////fyAgA "Jelly – Try It Online")
A pair of links that takes an integer argument and returns an RGB matrix on the (0 to 1) scale. Approach is the same as PBM output below but loses some bytes from the simpler output format.
---
# Previous PBM answer [Jelly](https://github.com/DennisMitchell/jelly), ~~49~~ 44 bytes
```
r0×€:⁸
×3‘ƊHḂ?Ƭ;Ɲ_/AÞṪçƊ+ṪƲƝẎŒṬµZL;L;FKṭ“P1 
```
[Try it online!](https://tio.run/##AVgAp/9qZWxsef//cjDDl@KCrDrigbgKw5cz4oCYxopI4biCP8asO8adXy9Bw57huarDp8aKK@G5qsayxp3huo7FkuG5rMK1Wkw7TDtGS@G5reKAnFAxIP///zIy "Jelly – Try It Online")
A full program that takes an integer argument and prints the contents of a PBM file.
Thanks to @cairdcoinheringaahing for some nice golfs totally 5 bytes!
## Example for 22:
[![Example image for 22](https://i.stack.imgur.com/x8PkR.jpg)](https://i.stack.imgur.com/x8PkR.jpg)
---
# Original SVG-based answer: [Jelly](https://github.com/DennisMitchell/jelly), 83 bytes
```
×3‘ƊHḂ?Ị¬$Ð¿µj”,$ƝKṭṀ,`$“¡×ȯFṗẓ"az⁺Ṭ*,ġẎlḣḂ⁷Ọ]Ẏɦ?÷hṖF.IØṣƘŻÇÄ<,Ḥ:ẆṡṂȮXȷḷ[eʂmJ]»Ỵ¤;"
```
[Try it online!](https://tio.run/##AagAV/9qZWxsef//w5cz4oCYxopI4biCP@G7isKsJMOQwr/CtWrigJ0sJMadS@G5reG5gCxgJOKAnMKhw5fIr0bhuZfhupMiYXrigbrhuawqLMSh4bqObOG4o@G4guKBt@G7jF3huo7Jpj/Dt2jhuZZGLknDmOG5o8aYxbvDh8OEPCzhuKQ64bqG4bmh4bmCyK5YyLfhuLdbZcqCbUpdwrvhu7TCpDsi////NDU "Jelly – Try It Online")
A full program taking an integer argument and printing an SVG.
For example, with 45:
```
<svg width="136" height="136"><path stroke="red" fill="none" d="M45,136 136,68 68,34 34,17 17,52 52,26 26,13 13,40 40,20 20,10 10,5 5,16 16,8 8,4 4,2 2,1"/></svg>
```
[![Example SVG](https://i.stack.imgur.com/Hm3ff.jpg)](https://i.stack.imgur.com/Hm3ff.jpg)
[Answer]
# [R](https://www.r-project.org/) >= 4.1, ~~81~~ 74 bytes
```
\(x,y=x){while(x>1)y=c(y,x<-c(x/2,3*x+1)[x%%2+1]);plot(y,c(y[-1],NA),"l")}
```
[Try it at RDRR.io!](https://rdrr.io/snippets/embed/?code=f%20%3C-%20function(x%2Cy%3Dx)%7Bwhile(x%3E1)y%3Dc(y%2Cx%3C-c(x%2F2%2C3*x%2B1)%5Bx%25%252%2B1%5D)%3Bplot(y%2Cc(y%5B-1%5D%2CNA)%2C%22l%22)%7D%0Af(45))
Note this uses RDRR because TIO doesn’t support graphical output. It also uses `function` in place of `\` since RDRR doesn’t support R 4.1.0 yet.
Thanks to @DominicVanEssen for saving 7 bytes!
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 70 bytes
```
Graphics@Line@Last@Reap[#//.a_/;a>1:>Last@Sow@{a,If[2∣a,a/2,3a+1]}]&
```
-17 bytes from @att
`63728127`
[![enter image description here](https://i.stack.imgur.com/C8eZR.png)](https://i.stack.imgur.com/C8eZR.png)
[Answer]
# Julia using GR, 121 99 77 bytes
Even better version by @MarcMush:
```
using GR
!x=while(X=x[end])>1 plot([x;],(x=[x;X%2>0 ? 3X+1 : X/2])[2:end])end
```
Improved version thanks to the tips found [here](https://codegolf.stackexchange.com/questions/24407/tips-for-golfing-in-julia):
```
using GR
c(a)=(i=1;while a[i]>1 a=[a;%(a[i],2)>0 ? 3a[i]+1 : a[i]/2];i+=1end;plot(a[1:i-1],a[2:i]))
```
What has been done:
* single-line notation for functions -10 bytes
* replace `push!` by array concatenation -3 bytes
* use input `a` as array - 6 bytes
* replace `end` by variable `i` that stores the length -3 bytes
Original version:
```
using GR
function c(x) a=[x]
while a[end]>1 push!(a,%(a[end],2)>0 ? 3a[end]+1 : a[end]/2)end
plot(a[1:end-1],a[2:end])end
```
Calling `c(27)` gives:
[![enter image description here](https://i.stack.imgur.com/1Qcqb.png)](https://i.stack.imgur.com/1Qcqb.png)
[Answer]
# [SageMath](https://doc.sagemath.org/), ~~81~~ \$\cdots\$ ~~74~~ 71 bytes
Saved 3 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!
```
f=lambda n,*r:n-1and f(c:=[n/2,3*n+1][n%2],*r,(n,c))or list_plot(r,1<2)
```
[Try it online!](https://sagecell.sagemath.org/?z=eJwFwUEKgCAQAMC7r_ASaG2EK1RIvkQkTBECW8P8P81kW8JzpcAJmnXe0KwCJZ5FNNbRgqBHmpR3NKCHNjlBEKWXtfFyf_18S-2igTpQMpbFqjfcFW7yB5BhGQ4=&lang=sage&interacts=eJyLjgUAARUAuQ==)
### f(63728127)
[![f(63728127)](https://i.stack.imgur.com/RojlB.png)](https://i.stack.imgur.com/RojlB.png)
[Answer]
# [Red](http://www.red-lang.org), ~~230~~ 212 bytes
```
func[n][a: to[]n while[n > 1][append a n: either odd? n[3 * n + 1][n / 2]]to-pair m: last sort copy a view[base 500x500 draw append[line]collect[while[a/2][keep as-pair a/1 / m * 500(first a: next a)/ m * 500]]]]
```
[Try it online!](https://tio.run/##PY7BasQwDETv/Yo5dreUbFJ6yaH7D70KH9RYIaZe2TjuJv16VyWwAiEYaeapiG@f4sk9zW3@0YnUEY@oiZxiW0IUUnygNzVnUQ@GjpBQFylI3l@h9IYzFC//R4oOg3M1vWYOBbcRkdeKNZWKKeVfs9@DbPTFq@D9ctmt4QtvOOIpBhU3pRhlqnTwuRscfYtk8HrEctcb52ZYsz/PoRjCnlbZbZ4eG2fV2h8 "Red – Try It Online")
I don't know if red has a scalable plotting mechanism, but this was what I managed to get using the draw dialect. All outputs are scaled to 500x500 and there may be some inaccuracies for larger inputs due to downscaling and pairs being integers.
In the red interpreter, you will have to redefine the function before each run because the words get messed up.
-4 after using default axes.
-18 bytes from Galen Ivanov.
## Output(n=12) (old)
[![enter image description here](https://i.stack.imgur.com/fn7di.png)](https://i.stack.imgur.com/fn7di.png)
[Answer]
# [Factor](https://factorcode.org/) + `ui.gadgets.charts ui.gadgets.charts.lines math.unicode`, ~~208~~ ~~204~~ 199 bytes
```
[ [ [ 3 dupn , odd? [ 3 * 1 + ] [ 2/ ] if dup 1 ≠ ] loop , ] f make chart new over supremum 1 + '[ 0 _ ] dup 2array >>axes line new COLOR: red >>color rot 2 clump >>data add-gadget "" open-window ]
```
It's quotation (anonymous function) that accepts an integer from the data stack and opens a window with the chart in it. This only works in recent-ish builds of Factor, as the `chart` gadget is fairly new; I used build `2074`. Here's what it looks like for an input of `27`:
[![enter image description here](https://i.stack.imgur.com/W6QuO.png)](https://i.stack.imgur.com/W6QuO.png)
Unfortunately, the `chart` gadget doesn't come with any constructors. It requires us to manually calculate axes, and build its subcomponents which themselves don't come with any constructors. This leads to a bit of verbosity.
[Answer]
# HTML + JS, 166 bytes
JS: 156 bytes
HTML: 14 bytes
This is a pretty basic implementation that renders to the DOM using an HTML canvas. A good chunk of the code is spent scaling the output to fit within the canvas. Anyone got any better ideas to handle this?
The input is specified inline in the code, set the number inside `x=[...]`.
```
x=[9];c=C.getContext`2d`;c.beginPath();while((z=x[0])-1)x.unshift(z%2?3*z+1:z/2);r=Math.max(...x)/99;x.map((a,i)=>c.lineTo(a/r,99-x[i-1]/r));c.stroke()
```
```
<canvas id=C>
```
[Answer]
# [Python 3](https://docs.python.org/3/) + matplotlib, 127 bytes
```
def f(n,r=[]):
 k=n
 while ~-n:n=[n//2,3*n+1][n%2];r+=[n]
 p.plot(*zip(*[[k]+r,r]),'-o');p.show()
import matplotlib.pyplot as p
```
-5 bytes thanks to @ovs!!!
[Answer]
# MATLAB 1999, ~~95~~ 84 bytes
-1 from Luis Mendo
```
n=input('');i=n;while i>1;i=(i+mod(i,2)*(5*i+2))/2;n=[n;i];end;plot([0/0;n],[n;0/0])
```
[![enter image description here](https://i.stack.imgur.com/KwaRQ.png)](https://i.stack.imgur.com/KwaRQ.png)
Even `A(2:)` and A(2:-1)` was unavailable at that time...
[Answer]
# Python + Pygame, 228 bytes
```
from pygame import*
d=display
n=int(input())
k=[]
while n>1:k+=[[n,n:=[n//2,3*n+1][n%2]]]
M=max(k)[0]
S=500
g=lambda s:[S*s[0]/M,S*s[1]/M]
s=d.set_mode([S,S])
for i,j in enumerate(k):draw.line(s,[99]*3,g(k[i-1]),g(j))
d.update()
```
No TIO link because Pygame is not supported there.
Reversed y-axis.
I could save one byte by setting `S` to 99 or something, but I chose not to for easier viewing. I could also change `[99]*3` to `[9]*3` but I chose not to for easier viewing.
Here is an example for input 63728127:
[![Example](https://i.stack.imgur.com/IEp3b.png)](https://i.stack.imgur.com/IEp3b.png)
]