0

I have plotted a graph on matplotlib and am trying to create a legend. How do i get matplotlib to create its own legend using the colour markers it has used to differentiate my types of data?

My data is read from a csv file that contains the labels for each type of shape.

My graph

My code looks like this:

data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv")
    X1 = np.array(data_df[features2].values)
    y1 = np.array(data_df[features3].values)

    plt.scatter(X1[:, 0],y1, c=y, cmap=plt.cm.Paired)
    plt.axis([0, 17, 0, 200])
    plt.ylabel("Maximum Angle (Degrees)")
    plt.xlabel("Number Of Sides")
    plt.title('Original 450 Test Shapes')

    plt.legend()
    plt.show()

I have tried this:

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)

But I keep getting this error:

    handles, labels = ax.get_legend_handles_labels()
UnboundLocalError: local variable 'ax' referenced before assignment

EDIT:

I tried this:

features_of_labels = ["Circle", "Equilateral Triangle", "Right Angle Triangle",
                     "Obtuse Triangle", "Acute Triangle", "Square", "Rectangle",
                     "Parallelogram", "Seal"]

data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv")
X1 = np.array(data_df[features2].values)
y1 = np.array(data_df[features3].values)
l = np.array(data_df[features_of_labels].values)

But i get the following error: KeyError: "['Circle' 'Equilateral Triangle' 'Right Angle Triangle' 'Obtuse Triangle'\n 'Acute Triangle' 'Square' 'Rectangle' 'Parallelogram' 'Seal'] not in index"

However if i change features_of_labels to header and header = ["Label"] it works but prints out every label like shown in the next picture.

enter image description here

Thom Elliott
  • 197
  • 3
  • 6
  • 18
  • Try `ax = plt.gca()` before that line. – mechanical_meat Apr 01 '17 at 15:16
  • @bernie i get this error: `UserWarning: No labelled objects found. Use label='...' kwarg on individual plots.` – Thom Elliott Apr 01 '17 at 15:20
  • 1
    So did you do what the warning told you? You should also have a look at [Question 1](http://stackoverflow.com/questions/37812325/pandas-scatter-plot-with-different-color-legend-for-each-point), [Question 2](http://stackoverflow.com/questions/30505407/create-legend-for-scatter-plot-using-the-label-of-the-samples-in-matplotlib), and [Question 3](http://stackoverflow.com/questions/8017654/how-to-add-legend-for-scatter) and using the aquired knowledge to improve your question. What do you want to achieve and in how far those techniques do not help you? – ImportanceOfBeingErnest Apr 01 '17 at 15:49
  • @ImportanceOfBeingErnest I did move the lines but i still get the same error anywhere i move the lines. I tried to change question 1 to my data but i keep getting `KeyError: 0` – Thom Elliott Apr 01 '17 at 16:04

1 Answers1

0

Here is an example:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt


# data for example
y1 = [i for i in range(10)]
y2 = [i for i in range(10)]
colors = ['m','b','g','m','b','g','m','b','g','g']
lables = ['m','b','g','m','b','g','m','b','g','g']

plt.scatter(y1, y2,c=colors, cmap=plt.cm.Paired)

# Match colors and labels,remove duplicates
colors_lables = zip(colors, lables)
colors_lables = list(set(colors_lables))
lables = [lable for color,lable in colors_lables]

# create some patchs of colors
lables_patchs = []
for item in c_l:
    add_patch = mpatches.Patch(color=item[0], label=item[1])
    lables_patchs.append(add_patch)

plt.legend(lables_patchs, lables)

plt.show()

And the picture we get: enter image description here

You can match your colors and lables,remove duplicates,and create some patchs of colors for your legend.

Further more,you can make some dot of colors for your legend

lables_patchs = []
for item in c_l:
    # here, use scatter()
    add_patch = plt.scatter([],[],color=item[0], label=item[1])
    lables_patchs.append(add_patch)

And you will get : enter image description here

hxysayhi
  • 1,888
  • 18
  • 25