我们如何根据颜色标记散点图的图例

How can we mark legend for a scatter plot based on color

我正在绘制图表以可视化 运行几种排序算法在不同数据大小上的宁时间。条件是 运行ning 时间应该在 y 轴上,数据大小在 x-axis.I 通过对数据大小采取 运行 次不同算法并给出每个标记不同的颜色。同样,我绘制了其他 3 个数据大小,但不同算法使用相同的颜色。我想在图表中添加一个图例,以便用户理解这个特定的色点对应于这个特定的算法。我想不出一个合适的方法。我在网上搜索了一些场景,他们根据不同的散点图添加了图例。但是,我想为基于颜色的点添加图例。

此外,对于这种情况,您能否建议一个更好的绘图曲线。

这是我用于图形生成的代码。

def visualize_datasize(dataset):
    datasize=len(dataset)
    for i in range(4,0,-1):
        run_time=getRunTime(dataset,int(datasize/i))
        plt.scatter([int(datasize/i)]*5,run_time,color=['red','green','blue','yellow','black'])
    plt.xlabel('Size of the dataset')
    plt.ylabel('Run time')
    plt.title('Run time vs datasize for various sorting algorithms')
    plt.show()

最简单、最一致的方法是为每个算法绘制散点图。此外,您可能希望为此使用面向对象的接口。

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

def calculate_runtimes(algo, data, sizes):
    if algo == 'name1':
        # return timings for algorithm 1 given data at given sizes
    elif algo == 'name2':
        # ...

algo_labels = ['name1', 'name2', 'name3', 'name4', 'name5']
sizes = [1, 2, 4, 8, 16]
algo_runtimes = {name: calculate_runtimes(name, dataset, sizes) for name in algo_labels}
colors = ['red', 'green', 'blue', 'yellow', 'black']
x_positions = [len(dataset)*size for size in sizes]

for (label, runtimes), color in zip(algo_runtimes.items(), colors):
    ax.scatter(x_positions, runtimes, color=color, label=label)

ax.legend()