# How to plot a complex number in python using matplotlib ?

Published: April 03, 2020

An example of how to plot a complex number in python using matplotlib:

### Plot a complex number

Let's consider the following complex number

````z1 = 4 + 2i`
```

Example of how to create a python function to plot a geometric representation of a complex number:

````import matplotlib.pyplot as plt`
`import numpy as np`
`import math`

`z1 = 4.0 + 2.*1j`

`x_min = -5.0`
`x_max = 5.0`

`y_min = -5.0`
`y_max = 5.0`

`def plot_complex_number_geometric_representation(z,x_min,x_max,y_min,y_max):`

`    fig = plt.figure()`

`    ax = plt.gca()`

`    ax.spines['left'].set_position('zero')`
`    ax.spines['right'].set_color('none')`
`    ax.spines['bottom'].set_position('zero')`
`    ax.spines['top'].set_color('none')`

`    a = [0.0,0.0]`
`    b = [z.real,z.imag]`

`    head_length = 0.2`

`    dx = b[0] - a[0]`
`    dy = b[1] - a[1]`

`    vec_ab = [dx,dy]`

`    vec_ab_magnitude = math.sqrt(dx**2+dy**2)`

`    dx = dx / vec_ab_magnitude`
`    dy = dy / vec_ab_magnitude`

`    vec_ab_magnitude = vec_ab_magnitude - head_length`

`    ax = plt.axes()`

`    ax.arrow(a[0], a[1], vec_ab_magnitude*dx, vec_ab_magnitude*dy, head_width=head_length, head_length=head_length, fc='black', ec='black')`

`    plt.scatter(a[0],a[1],color='black',s=2)`
`    plt.scatter(b[0],b[1],color='black',s=2)`

`    #ax.annotate('A', (a[0]-0.4,a[1]),fontsize=14)`
`    ax.annotate('z1', (b[0]+0.3,b[1]),fontsize=10)`

`    ax.text(0, y_max+0.5, r'Img', fontsize=10, horizontalalignment='center')`
`    ax.text(x_max+0.5, 0, r'Real', fontsize=10, verticalalignment='center')`

`    plt.xlim(x_min,x_max)`
`    plt.ylim(y_min,y_max)`

`    plt.grid(True,linestyle='--')`

`    plt.savefig('plot_complex_number_geometric_representation_01.png', bbox_inches='tight')`
`    #plt.show()`
`    plt.close()`

`plot_complex_number_geometric_representation(z1,x_min,x_max,y_min,y_max)`
```

Image

of