Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mpld3 plot, annotations issues

I'm using mpld3 to display graphs on an intranet website. I'm using the option of saving the graph to a dict and render it on the client side using mpld3.js.

The graph renders fine except when I want to use annotations. Those ones are clearly offset. And I don't understand why, because even if I set the offset to (0, 0), the annotations are still way off.

To illustrate this, I have copied and pasted the example given in this post: Matplotlib: How to put individual tags for a scatter plot

Here is the image as correctly generated by matplotlib: Matplotlib version

Here is the one made with mpld3: enter image description here

Note that both image are generated at the same time using the code in the link mentioned above. The matplotlib one is made using:

plt.show()

and then manually saved.

The one from mpld3 is made using:

 graph_data = json.dumps(fig_to_dict(fig))

Then graph_data is generated on the client side using mpld3.js, which works perfectly fine except when using annotations.

Do you have any idea why it behaves like this? Eventually I could just display the images generated directly from matplotlib, but the have interactive chart is a nice bonus.

like image 914
Julien Avatar asked Aug 24 '26 19:08

Julien


1 Answers

It appears that plt.annotate is a mpl feature that is not yet supported in mpld3. I've added it to the list of missing features. Pull requests welcome!

For a hacky work-around, you can use plt.text to get the words and plt.plot to make any additional embellishments:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(12345) # set seed for reproducibility

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker = 'o', c = data[:, 2], s = data[:, 3]*1500,
    cmap = plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.text(x-.05, y+.05,
        label,
        ha = 'right', va = 'bottom')
    plt.plot([x-.05,x], [y+.05,y], 'k-')

Here is a notebook that shows it in action. You might also be interested in the HTML Tooltips plugin.

like image 89
Abraham D Flaxman Avatar answered Aug 26 '26 10:08

Abraham D Flaxman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!