📜  如何使用 Matplotlib 在Python中绘制复数?

📅  最后修改于: 2022-05-13 01:55:09.624000             🧑  作者: Mango

如何使用 Matplotlib 在Python中绘制复数?

在本文中,我们将学习如何使用 Matplotlib 在Python中绘制复数。让我们讨论一些概念:

  • Matplotlib Matplotlib 是一个了不起的Python可视化库,用于二维数组绘图。 Matplotlib 是一个基于 NumPy 数组的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈一起使用。它是由 John Hunter 在 2002 年推出的。
  • 复数:复数是可以表示为a+bi形式的数,其中a和b为实数,i表示虚数单位,满足方程i2=-1。因为没有实数满足这个方程,所以 i 被称为虚数。
  • Python中的复数:复数用“x+yi”表示。 Python使用函数complex(x,y) 将实数 x 和 y 转换为复数。实部可以使用函数real()访问,虚部可以用imag()表示。

方法:

  1. 导入库。
  2. 创建复数数据
  3. 从复数数据中提取实部和虚部
  4. 绘制提取的数据。

例子:

要绘制复数,我们必须提取其实部和虚部并提取和创建数据,我们将使用以下示例中解释的一些方法:

示例 1 :(在实数和虚数数据上使用复数的简单图)

Python3
# 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()


Python3
# 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()


Python3
# 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()


输出 :

示例 2:(使用 numpy 提取实部和虚部)

蟒蛇3

# 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()

输出 :

示例3:(使用numpy创建复数数据并提取实部和虚部)

蟒蛇3

# 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()

输出 :