user2006134
user2006134

Reputation: 5

How to put a legend inside a loop with one by one data point (or outside) in Python?

In matplotlib, I am using a loop to plot a graph, with each step only plotting one data point (X[index], Y[index]) with a specific color C[index], so that it will assign a color to each point. In total, I use 8 colors to represent my data points, so I hope I can have a legend with these 8 colors and each one represents one meaning.

This is my code. Thanks for help. : )

for index in range(0,len(X)):
  plt.plot(X[index],Y1[index], marker = 'o', markersize = 10, color = C[index])  
  plt.xlabel("the percentage of students' credit hours found in instructor data", fontsize=14, color ="blue")
  plt.ylabel("total number of writing assinments", fontsize=14, color="blue")
  plt.axis([0, 100, 0, max(Y1)]) 
plt.show()

Upvotes: 0

Views: 580

Answers (1)

cyfur01
cyfur01

Reputation: 3302

An example straight from the matplotlib documentation:

The kwargs can be used to set line properties (any property that has a set_* method). You can use this to set a line label (for auto legends), linewidth, anitialising, marker face color, etc. Here is an example:

    plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)
    plot([1,2,3], [1,4,9], 'rs',  label='line 2')
    axis([0, 4, 0, 10])
    legend()

So, if you set the label property for each line, you should just be able to call legend() afterwards and it will automagically generate the legend with appropriate labels.

If you want to do something fancier with the legend, they also have documentation for that.

Upvotes: 2

Related Questions