使用 c 参数更改标记颜色
在此步骤中,我们将自定义标记的颜色。与大小类似,你可以使用 plt.scatter() 函数中的 c 参数来控制颜色。
你可以传递一个单一的颜色名称(例如 'red')来使所有标记颜色相同,或者传递一个颜色数组来为每个标记指定特定颜色。让我们为每个点分配一个唯一的颜色。
更新你的 main.py 文件,以包含一个 colors 数组并将其传递给 c 参数。
import numpy as np
import matplotlib.pyplot as plt
## Data for plotting
x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])
sizes = np.array([20, 50, 100, 200, 500, 1000, 60, 90, 10, 300, 600, 800, 75])
colors = np.array(["red", "green", "blue", "yellow", "pink", "black", "orange", "purple", "beige", "brown", "gray", "cyan", "magenta"])
## Create scatter plot with custom sizes and colors
plt.scatter(x, y, s=sizes, c=colors)
## Save the plot to a file
plt.savefig('/home/labex/project/scatter_plot_colors.png')
print("Scatter plot with custom colors saved to scatter_plot_colors.png")
我们现在已经添加了一个包含颜色名称的 colors 数组,并将函数调用更新为 plt.scatter(x, y, s=sizes, c=colors)。
从终端执行脚本:
python3 main.py
再打开一次 scatter_plot_colors.png。你将看到一个多彩的散点图,其中每个点的大小和颜色都与我们在数组中定义的相同,但颜色不同。