使用 matplotlib 手动设置图例颜色 Python
Manually set legend colors using matplotlib Python
我尝试绘制以下线图,但我很难手动设置图例颜色。目前图例颜色与线条颜色不匹配。任何帮助都会非常有帮助。谢谢。
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"])
对于图例的自定义生成,您可以使用此 link。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
您可以在向绘图添加数据时创建符号,然后将图例审核为唯一条目,如下所示:
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)
一种简单的方法是保存每种类型元素的句柄。在下面的代码中,handleA, = plt.plot(..., label='A')
将 plt.plot
创建的行元素存储到名为 handleA
的变量中。句柄将保留其标签以在图例中自动使用。 (需要一个逗号,因为 plt.plot
总是 returns 一个元组,即使只创建了一个行元素。)
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()
我尝试绘制以下线图,但我很难手动设置图例颜色。目前图例颜色与线条颜色不匹配。任何帮助都会非常有帮助。谢谢。
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"])
对于图例的自定义生成,您可以使用此 link。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
您可以在向绘图添加数据时创建符号,然后将图例审核为唯一条目,如下所示:
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)
一种简单的方法是保存每种类型元素的句柄。在下面的代码中,handleA, = plt.plot(..., label='A')
将 plt.plot
创建的行元素存储到名为 handleA
的变量中。句柄将保留其标签以在图例中自动使用。 (需要一个逗号,因为 plt.plot
总是 returns 一个元组,即使只创建了一个行元素。)
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()