Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing values displayed in top right corner of matplotlib figure

How can I change the values dislayed in the top right corner of matplot figure? By default it is showing coordinates of the current cursor position but I’d prefer it to show the value of displayed data for current x cursor’s coordinate. I marked these values in the attached picure. diagram

Here’s a simple code. Pls tell me how to solve described problem for this example:

from matplotlib import pyplot as plt
import soundfile as sf

data_mono = []
x_click = 0

# Loding an audio signal
data, sps = sf.read("stereo_v2.wav")

# Signal loaded by sf.read() is stereo (after plotting there are going to be
# 2 values for every sample) so we need to make it mono. This is what a loop
# down below is doing.
for i in range(0,len(data)):
    bufor = ((data[i][0] + data[i][1])/2)
    data_mono.append(bufor)

fig, ax = plt.subplots()
ax = plt.plot(data_mono)

# Below function is creating a vertical line in a place of left mouse click.
# Right click is deleting recently created line.
def click(event):
    global x_click
    x_click = event.xdata
    if event.button == plt.MouseButton.LEFT:
        global line
        line = plt.axvline(event.xdata)
    elif event.button == plt.MouseButton.RIGHT:
        plt.gca().lines[-1].remove()

# "Connecting" the cursor to above function.
cid = fig.canvas.mpl_connect('button_press_event', click)

# Loop displaying the plot and refreshing it every 0.05 second. When x coordinate
# of registered click is bigger than 0.9999 of the maximal x value loop
# will break.
while True:
    plt.pause(0.05)
    if x_click >= (len(data_mono))*0.9999:
        break

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to retrieve the x-value and use it as the index of your sound data list. As you have to check for the validity of the index, we define now a function NavigCoordin():

import numpy as np
from matplotlib import pyplot as plt
import soundfile as sf 


data_mono = []
x_click = 0

# Loding an audio signal
data, sps = sf.read("test.wav")

# Signal loaded by sf.read() is stereo (after plotting there are going to be
# 2 values for every sample) so we need to make it mono. This is what a loop
# down below is doing.
for i in range(0,len(data)):
    bufor = ((data[i][0] + data[i][1])/2)
    data_mono.append(bufor)

fig, ax = plt.subplots(figsize=(15, 4))
#don't overwrite your axis object - you need it later on
ax.plot(data_mono) 

#the function to determine the x-index and the corresponding y-value from the array 
#and return a string depending on the x-value
def NavigCoordin(x, y):
    if x>=0 and x<=len(data_mono):
        return f"x: {int(x+0.5)}, y: {data_mono[int(x+0.5)]:.4f}"
    else:
        return "outside the range"

#link the function to the axis object
ax.format_coord = NavigCoordin

# Below function is creating a vertical line in a place of left mouse click. 
# Right click is deleting recently created line.
def click(event):
    global x_click
    x_click = event.xdata
    if event.button == plt.MouseButton.LEFT:
        global line
        line = ax.axvline(event.xdata)
    elif event.button == plt.MouseButton.RIGHT:
        ax.lines[-1].remove()

# "Connecting" the cursor to above function.
cid = fig.canvas.mpl_connect('button_press_event', click)

# Loop displaying the plot and refreshing it every 0.05 second. When x coordinate
# of registered click is bigger than 0.9999 of the maximal x value loop
# will be break.
while True:
    plt.pause(0.05)
    if x_click >= (len(data_mono))*0.9999:
        break

Sample output:
enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading