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?
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.
https://github.com/mpld3/mplexporter/pull/54 should fix this issue!
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 ofyou can do
and the legend will include the colored markers.