📜  如何在 Matplotlib 中创建具有多种颜色的散点图?

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

如何在 Matplotlib 中创建具有多种颜色的散点图?

Matplotlib 是一个绘图库,用于在Python中创建静态、动画和交互式可视化。 Matplotlib可用于Python脚本、 Python和 IPython shell、Web 应用程序服务器以及各种图形用户界面工具包,如 Tkinter、awxPython 等。

为了在matplotlib中创建具有多种颜色的散点图,我们可以使用各种方法:

方法#1 :使用参数标记颜色即c

例子:

使用c参数来描绘不同颜色的散点图。

Python3
# import required module
import matplotlib.pyplot as plt
  
# first data point
x = [1, 2, 3, 4]
y = [4, 1, 3, 6]
  
# depict first scatted plot
plt.scatter(x, y, c='green')
  
# second data point
x = [5, 6, 7, 8]
y = [1, 3, 5, 2]
  
# depict second scatted plot
plt.scatter(x, y, c='red')
  
# depict illustrattion
plt.show()


Python3
# import required modules
import matplotlib.pyplot as plt
import numpy
  
# assign data points
a = numpy.array([[9, 1, 2, 7, 5, 8, 3, 4, 6],
                 [4, 2, 3, 7, 9, 1, 6, 5, 8]])
  
# assign categories
categories = numpy.array([0, 1, 2, 0, 1, 2, 0, 1, 2])
  
# use colormap
colormap = numpy.array(['r', 'g', 'b'])
  
# depict illustration
plt.scatter(a[0], a[1], s=100, c=colormap[categories])
plt.show()


Python3
# import required modules
import matplotlib.pyplot as plt
import numpy
  
# assign data points
a = numpy.array([[1, 2, 3, 4, 5, 6, 7, 8, 9],
                 [9, 8, 7, 6, 5, 4, 3, 2, 1]])
  
# assign categories
categories = numpy.array([0, 1, 1, 0, 0, 1, 1, 0, 1])
  
# assign colors using color codes
color1 = (0.69411766529083252, 0.3490196168422699, 
          0.15686275064945221, 1.0)
color2 = (0.65098041296005249, 0.80784314870834351,
          0.89019608497619629, 1.0)
  
# asssign colormap
colormap = numpy.array([color1, color2])
  
# depict illustration
plt.scatter(a[0], a[1], s=500, c=colormap[categories])
plt.show()


输出:

方法#2 :使用颜色图

颜色图实例用于将数据值(浮点数)从区间 [0, 1] 转换为 RGBA 颜色。

示例 1:

使用颜色图以 RGB 颜色描绘散点图。

蟒蛇3

# import required modules
import matplotlib.pyplot as plt
import numpy
  
# assign data points
a = numpy.array([[9, 1, 2, 7, 5, 8, 3, 4, 6],
                 [4, 2, 3, 7, 9, 1, 6, 5, 8]])
  
# assign categories
categories = numpy.array([0, 1, 2, 0, 1, 2, 0, 1, 2])
  
# use colormap
colormap = numpy.array(['r', 'g', 'b'])
  
# depict illustration
plt.scatter(a[0], a[1], s=100, c=colormap[categories])
plt.show()

输出:

示例 2:

在这里,我们使用颜色代码手动分配颜色图

蟒蛇3

# import required modules
import matplotlib.pyplot as plt
import numpy
  
# assign data points
a = numpy.array([[1, 2, 3, 4, 5, 6, 7, 8, 9],
                 [9, 8, 7, 6, 5, 4, 3, 2, 1]])
  
# assign categories
categories = numpy.array([0, 1, 1, 0, 0, 1, 1, 0, 1])
  
# assign colors using color codes
color1 = (0.69411766529083252, 0.3490196168422699, 
          0.15686275064945221, 1.0)
color2 = (0.65098041296005249, 0.80784314870834351,
          0.89019608497619629, 1.0)
  
# asssign colormap
colormap = numpy.array([color1, color2])
  
# depict illustration
plt.scatter(a[0], a[1], s=500, c=colormap[categories])
plt.show()

输出: