![](/img/trans.png)
[英]The game over line isn't working. Why isn't it correctly displaying the games won and lost?
[英]Why isn't the legend in matplotlib correctly displaying the colors?
我有一個圖,其中顯示了3種不同的線圖。 因此,我要明確指定圖例以顯示3種顏色,每種圖分別顯示一種。 下面是一個玩具示例:
import matplotlib.pyplot as plt
for i in range(1,20):
if i%3==0 and i%9!=0:
plt.plot(range(1,20),[i+3 for i in range(1,20)], c='b')
elif i%9==0:
plt.plot(range(1,20),[i+9 for i in range(1,20)], c='r')
else:
plt.plot(range(1,20),range(1,20), c='g')
plt.legend(['Multiples of 3 only', 'Multiples of 9', 'All the rest'])
plt.show()
但是圖例無法正確顯示顏色。 為什么會這樣以及如何解決呢?
解決了:
import matplotlib.pyplot as plt
my_labels = {"x1" : "Multiples of 3", "x2" : "Multiples of 9","x3":'All of the rest'}
for i in range(1,20):
if i%3==0 and i%9!=0:
plt.plot(range(1,20),[i+3 for i in range(1,20)], c='b', label = my_labels["x1"])
my_labels["x1"] = "_nolegend_"
elif i%9==0:
plt.plot(range(1,20),[i+9 for i in range(1,20)], c='r', label = my_labels["x2"])
my_labels["x2"] = "_nolegend_"
else:
plt.plot(range(1,20),[j for j in range(1,20)],c='g', label = my_labels["x3"])
my_labels["x3"] = "_nolegend_"
plt.legend(loc="best") #
plt.show()
請參閱doc
中提供的鏈接此鏈接,這將有答案解釋幫助。
我嘗試了Rex5的答案; 它在這個玩具示例中有效,但在我的實際情節中(下),由於某種原因,它仍然產生錯誤的圖例。
相反,按照Rex5提供的鏈接中的建議,以下解決方案可以工作(在玩具示例和我的實際情節中),並且也更簡單:
for i in range(1,20):
if i%3==0 and i%9!=0:
a, = plt.plot(range(1,20),[i+3 for i in range(1,20)], c='b')
elif i%9==0:
b, = plt.plot(range(1,20),[i+9 for i in range(1,20)], c='r')
else:
c, = plt.plot(range(1,20),[j for j in range(1,20)],c='g')
plt.legend([a, b, c], ["Multiples of 3", "Multiples of 9", "All of the rest"])
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.