0

I'm attempting to use a dataframe to create a scatter plot. Here's an example of what the dataframe looks like:

----------------------------------------------
| Index   |   x  |   y  |  color   |  name   |
----------------------------------------------
|    0    |  4.3 |  2.2 |    'b'   |  'First'|
----------------------------------------------
|    1    |  2.3 |  3.2 |    'c'   |  'Secd' |
----------------------------------------------

The code I'm using to plot looks like this:

plt.scatter(dframe['x'], dframe['y'], color=dframe['color'], label=dframe['name'])
plt.title('Title')
plt.xlabel('X label')
plt.ylabel('Y label')
plt.xlim(0, 10)
plt.ylim(0, 10)
plt.legend(scatterpoints=1, loc='lower left', fontsize=10)
plt.show()

For whatever reason, this adds 1 item to the legend and the label for that item is the entire 'name' column repeated 2x.

How can I get the legend to display each item separately in the name column and only show that column once?

Thanks!

As info, I have tried the following to no avail:

plt.legend(dframe['name'], loc = 'lower....

for i in range(len(dframe['name'])):
    plt.legend(dframe['name'][i], loc = .. 

plt.legend([dframe['name']], loc = 'lower....

1 Answer 1

2

plt.scatter gets only one legend label per call. If you want to have a label for each point, you'd have to do something like this:

for index, row in dframe.iterrows():
    plt.scatter(row['x'], row['y'], color=row['color'], label=row['name'])
plt.title('Title')
plt.xlabel('X label')
plt.ylabel('Y label')
plt.xlim(0, 10)
plt.ylim(0, 10)
plt.legend(scatterpoints=1, loc='lower left', fontsize=10)
plt.show()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.