我嘗試繪制以下線圖,但我很難手動設定圖例顏色。目前,圖例顏色與線條顏色不匹配。任何幫助都會非常有幫助。謝謝你。
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"])
uj5u.com熱心網友回復:
一種簡單的方法是為每種型別的元素保存句柄。在下面的代碼中,handleA, = plt.plot(..., label='A')將創建的線元素存盤plt.plot到名為 的變數handleA中。句柄將保留其標簽以在圖例中自動使用。(需要逗號,因為plt.plot總是回傳一個元組,即使只創建了一個行元素。)
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()

uj5u.com熱心網友回復:
對于圖例的自定義生成,您可以使用此鏈接。撰寫自定義圖例
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()
輸出將是這樣的: 輸出
uj5u.com熱心網友回復:
您可以在將資料添加到繪圖時創建符號,然后將圖例審核為唯一條目,如下所示:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440765.html
標籤:Python matplotlib 海运 图例属性
