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?

Joseph E
  • 33
  • 7
  • see [here](https://stackoverflow.com/questions/44998205/labeling-points-in-matplotlib-scatterplot) [here](https://stackoverflow.com/questions/44630279/display-numbers-instead-of-points-using-pyplot) and [here.](https://stackoverflow.com/questions/14432557/matplotlib-scatter-plot-with-different-text-at-each-data-point) – Darshan Nov 27 '20 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. – Joseph E Nov 27 '20 at 23:06

1 Answers1

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

swatchai
  • 17,400
  • 3
  • 39
  • 58