Search code examples
pythongraphingmatplotlib

Pyplot - Label Plots


I am having a nightmare of a time trying to label data with pyplot.

I am currently plotting all of my data like this: plt.plot(data).

data is an array that has a column of total costs, and then other columns for sub costs

I would like to add a legend and label each of the data lists appropriately. I can't seem to get the legend to work though. plt.legend(('Column 1','Column 2','etc.) , loc =1) and other things like that did not work. If I plot each column individually, it stops working correctly for some reason.

I look forward and thank you for any advice.

EDIT:

for i in range(1,days):
    data.append(totalCost(i)) #cost returns retVal, construction, gas, and wage
plt.ylabel('Cost in US Dollars') 
plt.title('Economic Cost over Time')

plt.plot(data)
plt.legend(('Total','Construction','Gas','Wage'),loc=1) # Legend is blank

EDIT 2: Instead of having the code in different locations in my program, I reorganized it and centralized everything. With those changes, the legend started working, and everything seems to be resolved. I have no idea what the issue was though.

plt.plot(data)
plt.legend(('Total Cost', 'Construction Cost', 'Gas Cost','Wage Cost'),loc=0)
plt.grid(False)
plt.xlabel('Time (Days)')
plt.ylabel('Cost in US Dollars')
plt.title('Economic Cost over Time')
print ('   Close the Graph to Continue Using this Model')
plt.show()

Solution

  • Your code properly displays a legend, with Matplotlib 1.1 on Mac OS X, provided that:

    • Matplotlib is put in interactive mode at the beginning: plt.ion()
    • The code ends with plt.show(), for instance.

    Upgrading Matplotlib might also help.

    A last possible solution would be to indeed plot each line separately with its own label: plt.plot(<single line data>, label='Construction'), etc., and the plot the legend with plt.legend(loc='best').