[英]fix label legend python
我正在嘗試為具有相同數字的“域”使用相同的 label。 我該怎么做? 我希望每個域號都使用相同的顏色...
d = {'selected_peaks': [487, 537, 181, 139], 'timeStep': [24250000.0, 26750000.0, 9000000.0, 6900000.0]
, 'F': [868.7655, 713.4191, 584.4315, 698.3004], 'domain': [2, 2, 3, 3]}
for i in range(len(d['selected_peaks'])):
plt.plot(d['timeStep'][i], d['F'][i], 'o', label='domain '+str(d['domain'][i]))
plt.legend()
只需創建 colors 的字典並使用color
參數引用它們。
import matplotlib.pyplot as plt
d = {'selected_peaks': [487, 537, 181, 139], 'timeStep': [24250000.0, 26750000.0, 9000000.0, 6900000.0]
, 'F': [868.7655, 713.4191, 584.4315, 698.3004], 'domain': [2, 2, 3, 3], }
colors = {2:'red', 3:'green'}
for i in range(len(d['selected_peaks'])):
plt.plot(d['timeStep'][i], d['F'][i], 'o', label='domain '+str(d['domain'][i]), color=colors[d['domain'][i]])
plt.legend()
Although the plot can definitely be created only employing matplotlib, the problem at hand is very suited to present the data as a pandas dataframe and use seaborn to plot.
只需將“域”列的名稱作為hue
參數傳遞,就會自動為每個域創建一種顏色,並自動添加一個圖例,並刪除所有雙條目。 如果您不喜歡默認的 colors,您可以選擇顏色圖、創建顏色圖或提供 colors 列表作為palette
參數。 X 軸和 Y 軸的相應標簽也會使用列名自動設置。
from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns
d = {'selected_peaks': [487, 537, 181, 139], 'timeStep': [24250000.0, 26750000.0, 9000000.0, 6900000.0],
'F': [868.7655, 713.4191, 584.4315, 698.3004], 'domain': [2, 2, 3, 3]}
df = pd.DataFrame(d)
sns.scatterplot('timeStep', 'F', marker='o', hue='domain', palette='tab10', data=df)
plt.show()
將你的問題分成兩個答案你的問題,但它看起來不是很干凈......
import matplotlib.pyplot as plt
d = {'selected_peaks': [487, 537, 181, 139],
'timeStep': [24250000.0, 26750000.0, 9000000.0, 6900000.0],
'F': [868.7655, 713.4191, 584.4315, 698.3004], 'domain': [2, 2, 3, 3]}
if 2 in d['domain']:
for i in range(len(d['selected_peaks'][:2])):
plt.plot(d['timeStep'][i], d['F'][i], 'o', c='black',
label='domain '+str(d['domain'][i]))
plt.legend()
if 3 in d['domain']:
for i in range(len(d['selected_peaks'][2:4])):
plt.plot(d['timeStep'][i+2], d['F'][i+2], 'o', c='red',
label='domain '+str(d['domain'][i+2]))
plt.legend()
根據域的值指定顏色,使用顏色變量,然后發送到 plt.plot() 命令:
if d["domain"][i] == 2:
color = "b"
elif d["domain"][i] == 3:
color = "r"
最終代碼變為:
import matplotlib.pyplot as plt
d = {
"selected_peaks": [487, 537, 181, 139],
"timeStep": [24250000.0, 26750000.0, 9000000.0, 6900000.0],
"F": [868.7655, 713.4191, 584.4315, 698.3004],
"domain": [2, 2, 3, 3],
}
for i in range(len(d["selected_peaks"])):
if d["domain"][i] == 2:
color = "b"
elif d["domain"][i] == 3:
color = "r"
plt.plot(
d["timeStep"][i],
d["F"][i],
"o",
color=color,
label="domain " + str(d["domain"][i]),
)
plt.legend()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.