nas
nas

Reputation: 2417

How to change the contents of the datacursor when using mpldatacursor

I have a simple code written to plot the red circles.

import matplotlib.pyplot as plt
import numpy as np
from mpldatacursor import datacursor

lines = plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
datacursor(lines)
plt.show()

The above code is generating pyplot as follows: enter image description here

My question is when I click on the red mark of the plot, how can I change the label (x, y) to custom label from the appeared popup?

Is it possible to show this pop up only for few second?

Upvotes: 3

Views: 2432

Answers (1)

Suever
Suever

Reputation: 65430

You need to use the formatter kwarg to customize the displayed data. For example to force the x and y values to both be integers, we can do something like the following:

datacursor(lines, formatter='x: {x:.0f}\ny: {y:.0f}'.format)

You can use any custom formatter to change the displayed text in any way including the labels themselves.

datacursor(lines, formatter='my_x: {x:.0f}\nmy_y: {y:.0f}'.format)

Rather than using str.format as shown above, you can even write an entire function to format your labels.

def myformatter(**kwarg):
    label = 'My custom label at point ({x:.0f}, {y:.0f})'.format(**kwarg)
    return label

datacursor(lines, formatter=myformatter)

Upvotes: 5

Related Questions