matplotlib 手动设置图例颜色

3zwtqj6y  于 2023-04-06  发布在  其他
关注(0)|答案(3)|浏览(175)

我尝试绘制下面的线图,但我有困难手动设置图例颜色。目前的图例颜色不匹配的线颜色。任何帮助将是非常有帮助的。谢谢。

import random
import matplotlib.pyplot as plt
random.seed(10)

data=[(i, i+random.randint(1,20), random.choice(list("ABC"))) for i in range(2000,2025)]

plt.figure(figsize=(14,8))
for x, y,z in data:
    a=(x,x+y)
    b=(y+random.random(),y+random.random())
    if z=="A":
        a=(x,x)
        plt.plot(a,b,"bo",linestyle="-", linewidth=0.4, color="blue")
    elif z=="B":
        plt.plot(a,b,"bo",linestyle="-", linewidth=0.4, color="green")
    else:
        plt.plot(a,b,"bo",linestyle="-", linewidth=0.4, color="red")
ax = plt.gca()
plt.legend(['A', 'B',"C"])
g52tjvyc

g52tjvyc1#

一个简单的方法是为每种类型的元素保存句柄。在下面的代码中,handleA, = plt.plot(..., label='A')plt.plot创建的line元素存储到一个名为handleA的变量中。句柄将保留其标签,以便在图例中自动使用。(需要逗号,因为plt.plot总是返回一个元组,即使只创建了一个line元素。)

import random
import matplotlib.pyplot as plt

random.seed(10)
data = [(i, i + random.randint(1, 20), random.choice(list("ABC"))) for i in range(2000, 2025)]

plt.figure(figsize=(14, 8))
for x, y, z in data:
    a = (x, x + y)
    b = (y + random.random(), y + random.random())
    if z == "A":
        a = (x, x)
        handleA, = plt.plot(a, b, '-o', linewidth=0.4, color="blue", label='A')
    elif z == "B":
        handleB, = plt.plot(a, b, '-o', linewidth=0.4, color="green", label='B')
    else:
        handleC, = plt.plot(a, b, '-o', linewidth=0.4, color="red", label='C')

plt.legend(handles=[handleA, handleB, handleC], bbox_to_anchor=(1.01, 1.01), loc='upper left')
plt.tight_layout()
plt.show()

bq3bfh9z

bq3bfh9z2#

要自定义生成图例,您可以使用此链接。Composing Custom Legends

from matplotlib.patches import Patch
from matplotlib.lines import Line2D

legend_elements = [Line2D([0], [0], color='b', lw=4, label='Line'),
                   Line2D([0], [0], marker='o', color='w', label='Scatter',
                          markerfacecolor='g', markersize=15),
                   Patch(facecolor='orange', edgecolor='r',
                         label='Color Patch')]

# Create the figure
fig, ax = plt.subplots()
ax.legend(handles=legend_elements, loc='center')

plt.show()

输出将如下所示:Output

huus2vyu

huus2vyu3#

您可以在向图中添加数据时创建符号,然后将图例检查为唯一条目,如下所示:

import random
import matplotlib.pyplot as plt
random.seed(10)

data=[(i, i+random.randint(1,20), random.choice(list("ABC"))) for i in range(2000,2025)]

plt.figure(figsize=(14,8))
for x, y,z in data:
    a=(x,x+y)
    b=(y+random.random(),y+random.random())
    if z=="A":
        a=(x,x)
        plt.plot(a,b, '-o', linewidth=0.4, color="blue", label='A')
    elif z=="B":
        plt.plot(a,b, '-o', linewidth=0.4, color="green", label='B')
    else:
        plt.plot(a,b, '-o', linewidth=0.4, color="red", label='C')

        

symbols, names = plt.gca().get_legend_handles_labels()
new_symbols, new_names = [], []
for name in sorted(list(set(names))):
    index = [i for i,n in enumerate(names) if n==name][0]
    new_symbols.append(symbols[index])
    new_names.append(name)
    
plt.legend(new_symbols, new_names)

相关问题