Mpld3: legend markers are not rendered in scatter plot

Created on 15 May 2015  路  4Comments  路  Source: mpld3/mpld3

I got a similar issue with scatter plot as #185. But framealpha hack is not effective here.

import numpy as np
import matplotlib.pyplot as plt
import mpld3

%matplotlib inline

mpld3.enable_notebook()

fig, ax = plt.subplots()
ax.scatter(np.random.randn(10), np.random.randn(10), color="red", label="data1")
ax.scatter(np.random.randn(10), np.random.randn(10), color="blue", label="data2")
ax.legend(title="Cluster", loc="best", framealpha=0)

It seems that svg has g elements for markers, but they are not rendered in legend. Are there something wrong with my code?

bug

Most helpful comment

Another more direct workaround is to leave the labels off of the scatter plots and then plot empty arrays with ax.plot() to populate the legend. So instead of

fig, ax = plt.subplots()
ax.scatter(np.random.randn(10), np.random.randn(10), color="red", label="data1")
ax.scatter(np.random.randn(10), np.random.randn(10), color="blue", label="data2")
ax.legend(title="Cluster", loc="best", framealpha=0)

you can do

fig, ax = plt.subplots()
ax.scatter(np.random.randn(10), np.random.randn(10), color="red")
ax.plot([], [], "o", color="red", label="data1")
ax.scatter(np.random.randn(10), np.random.randn(10), color="blue")
ax.plot([], [], "o", color="blue", label="data2")
ax.legend(title="Cluster", loc="best", framealpha=0)

and the legend will include the colored markers.

All 4 comments

Looks like a bug. If you come up with a fix, contributions are welcome!

Don't know if this is addressed at all, but in case anyone else needs a work around and only cares about showing the colors for certain labels in the legend (so it is at least worth something), I've been setting the font colors with

    l = ax.legend(fancybox=0)
    for i, text in enumerate(l.get_texts()):
        text.set_color(colors[i])

Another more direct workaround is to leave the labels off of the scatter plots and then plot empty arrays with ax.plot() to populate the legend. So instead of

fig, ax = plt.subplots()
ax.scatter(np.random.randn(10), np.random.randn(10), color="red", label="data1")
ax.scatter(np.random.randn(10), np.random.randn(10), color="blue", label="data2")
ax.legend(title="Cluster", loc="best", framealpha=0)

you can do

fig, ax = plt.subplots()
ax.scatter(np.random.randn(10), np.random.randn(10), color="red")
ax.plot([], [], "o", color="red", label="data1")
ax.scatter(np.random.randn(10), np.random.randn(10), color="blue")
ax.plot([], [], "o", color="blue", label="data2")
ax.legend(title="Cluster", loc="best", framealpha=0)

and the legend will include the colored markers.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

arnaudrenaud picture arnaudrenaud  路  4Comments

andreatramacere picture andreatramacere  路  8Comments

jakevdp picture jakevdp  路  4Comments

dmiller7115 picture dmiller7115  路  5Comments

omn14 picture omn14  路  17Comments