Open In App

How to plot a complex number in Python using Matplotlib ?

In this article we will learn how to plot complex number in Python using Matplotlib. Let’s discuss some concepts :

Approach:



  1. Import libraries.
  2. Create data of complex numbers
  3. Extract real and imaginary parts from complex numbers data
  4. Plot the extracted data.

Examples:

To plot complex numbers, we have to extract its real and imaginary part and to extract and create data, we will use some methods that are explained in below examples :



Example 1 : (Simple plot with complex numbers over real and imaginary data)




# import library
import matplotlib.pyplot as plt
  
# create data of complex numbers
data = [1+2j, -1+4j, 4+3j, -4, 2-1j, 3+9j, -2+6j, 5]
  
# extract real part
x = [ele.real for ele in data]
# extract imaginary part
y = [ele.imag for ele in data]
  
# plot the complex numbers
plt.scatter(x, y)
plt.ylabel('Imaginary')
plt.xlabel('Real')
plt.show()

Output :

Example 2 : (Using numpy for extracting real and imaginary parts)




# import libraries
import matplotlib.pyplot as plt
import numpy as np
  
# create data of complex numbers
data = np.array([1+2j, 2-4j, -2j, -4, 4+1j, 3+8j, -2-6j, 5])
  
# extract real part using numpy array
x = data.real
# extract imaginary part using numpy array
y = data.imag
  
# plot the complex numbers
plt.plot(x, y, 'g*')
plt.ylabel('Imaginary')
plt.xlabel('Real')
plt.show()

Output :

Example 3 : (Using numpy for creating data of complex numbers and extracting real and imaginary parts)




# import libraries
import matplotlib.pyplot as plt
import numpy as np
  
# create data of complex numbers using numpy
data = np.arange(8) + 1j*np.arange(-4, 4)
  
# extract real part using numpy
x = data.real
# extract imaginary part using numpy
y = data.imag
  
# plot the complex numbers
plt.plot(x, y, '-.r*')
plt.ylabel('Imaginary')
plt.xlabel('Real')
plt.show()

Output :


Article Tags :