2

I've written a simple plotting routine. The problem I'm having is that for each "dataset" I'm plotting, I'm getting two dots in the legend. See the figure with free-hand red arrows.

enter image description here

Here's the code:

from collections import OrderedDict
from itertools import cycle

import matplotlib.backends.backend_agg
from matplotlib.figure import Figure


def simple_scatter(data, colors='rbgcmyk', no_legend=False):
  """Create a simple scatter plot."""
  data = OrderedDict(data)
  fig = Figure()
  matplotlib.backends.backend_agg.FigureCanvasAgg(fig)
  ax = fig.add_subplot(111)
  colors = cycle(colors)
  for label, points in data.iteritems():
    x, y = tuple(zip(*points))[:2]
    ax.plot(x, y, 'o', color=next(colors), label=label)

  if not no_legend:
    ax.legend(loc='best', shadow=True, fancybox=True)

  return fig


figure = simple_scatter([('Foo', ((1, 2), (3, 4))),
                         ('Bar', ((2, 3), (3, 5))),
                         ('Baz', ((2, 2.5), (3, 4.5)))])
figure.savefig('foo.png')

Any ideas how to get this down to a single dot per dataset?

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • I am not sure but isn't it because you are using both x and y (label, points)? try ax.plot(x ...) only? – Joohwan Sep 23 '13 at 17:09
  • @Joowani -- I'm not sure I understand your comment. `ax.plot(x,...)` would plot the x-values as `y-values` with monotonically increasing x-values (which isn't what I want). – mgilson Sep 23 '13 at 17:14
  • @DSM -- Bias or not, that's the solution. Feel free to actually mark this as a duplicate. I considered deleting the question myself, but for whatever reason, none of my search terms dug up your answer ... So, perhaps this will make it easier for someone else to find. – mgilson Sep 23 '13 at 17:36
  • http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.legend <- api link – tacaswell Sep 23 '13 at 18:21

1 Answers1

3
ax.legend(loc='best', shadow=True, fancybox=True, numpoints=1)
  • 1
    Welcome to SO! While this answer is technically _correct_ and the question is a duplicate, could you possibly add some commentary to your answer? A link to the documentation? Make it a sscce? – tacaswell Sep 24 '13 at 04:03