简体   繁体   English

在 matplotlib 的 for 循环中添加 label 和图例

[英]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()

I tried to add a legend based on the columns on my matplotlib graph , I know I have to add labels in order for the legend to display.我尝试根据matplotlib graph上的列添加图例,我知道我必须添加标签才能显示图例。 This is my code, how do I do so in the for loop.这是我的代码,我如何在 for 循环中这样做。 Particularly this part:特别是这部分:

for country in gas:
    if country != 'Year':
        plt.plot(gas.Year, gas[country], marker = '.', label = ?)

you can pass the column name as label to plt.plot.您可以将列名作为 label 传递给 plt.plot。 Then, you can call plt.legend() to draw the legend.然后,您可以调用 plt.legend() 来绘制图例。 Example with dummy data:带有虚拟数据的示例:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM