0

I have some x,y data stored as dictionaries with the key as x and the value as y. I want to graph these on a scatter plot using matplotlib, with each dictionary treated as a category. What I've tried so far colors the points how I want but labels each point separately instead of as a group, producing dozens of identical labels in the legend at scale. Here's what I have, with some placeholder info:

dict1 = {1:2, 3:4, 5:6}
dict2 = {7:8, 9:10, 11:12}
dict3 = {13:14, 15:16, 17:18}

data = (dict1, dict2, dict3)
colors = ('r', 'g', 'b')
groups = ('First','Second','Third')

for datum, color, group in zip(data, colors, groups):
    for i in datum:
        x, y = i, datum[i]
        plt.scatter(x, y, c=color, label=group)

plt.legend(loc=2)
plt.show()

I've tried moving plt.scatter() out of the for i in datum loop, but that only plots one point per group, instead of each key:value pair. How do I get the legend to label these by category instead of by point?

2
  • see here here and here. Commented Nov 27, 2020 at 23:00
  • Those questions aren't about adjusting the legend. I want to put one label per group in the legend, instead of duplicate labels for each point. Commented Nov 27, 2020 at 23:06

1 Answer 1

1

The modified code below will plot the data as required. Note the option label=group that handles legend's items to get the group names as defined in groups=('First','Second','Third').

import matplotlib.pyplot as plt

dict1 = {1:2, 3:4, 5:6}
dict2 = {7:8, 9:10, 11:12}
dict3 = {13:14, 15:16, 17:18}

data = (dict1, dict2, dict3)
colors = ('r', 'g', 'b')
groups = ('First','Second','Third')

for datum, color, group in zip(data, colors, groups):
    plt.scatter(datum.keys(), datum.values(), c=color, label=group)

plt.legend(loc=2)
plt.show()

Output:

dictdata

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.