[英]Add label and legend in the for loop for matplotlib
plt.figure(figsize = (8,5))
plt.title('Gas Prices over time in USD', fontdict={'fontname': 'Calibri', 'fontsize': 20})
for country in gas:
if country != 'Year':
plt.plot(gas.Year, gas[country], marker = '.')
plt.xticks(gas.Year[::3].tolist()+[2011])
plt.xlabel('Year')
plt.ylabel('US Dollars Per Gallon')
plt.show()
我嘗試根據matplotlib graph
上的列添加圖例,我知道我必須添加標簽才能顯示圖例。 這是我的代碼,我如何在 for 循環中這樣做。 特別是這部分:
for country in gas:
if country != 'Year':
plt.plot(gas.Year, gas[country], marker = '.', label = ?)
您可以將列名作為 label 傳遞給 plt.plot。 然后,您可以調用 plt.legend() 來繪制圖例。 帶有虛擬數據的示例:
gas = pd.DataFrame({'Year': np.arange(10)+2010, 'Cameroon':np.random.randint(0,10,10), 'Nepal':np.random.randint(0,10,10)})
plt.figure(figsize = (8,5))
plt.title('Gas Prices over time in USD', fontdict={'fontname': 'Calibri', 'fontsize': 20})
for country in gas:
if country != 'Year':
plt.plot(gas.Year, gas[country], marker = '.', label=country)
plt.xticks(gas.Year[::3].tolist()+[2011])
plt.xlabel('Year')
plt.ylabel('US Dollars Per Gallon')
plt.legend()
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.