Matplotlib.pyplot.ginput(): get two y-values for one x-value from two-line plot

498 Views Asked by At

Currently, I use the following piece of code to get function values by clicking into the plot, and this works fine for one curve:

data = pd.read_csv('filename')
plot = data.plot(x='column1', y='column2')
plt.show()
input_values = plt.ginput(n=0)
plt.close()

I would now like to simultaneously plot a second curve and obtain y-values from both plots with one click that determines the x-value. Thanks for your help!

1

There are 1 best solutions below

0
Mr. T On

A minimal working example could look like this:

from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
    
#data generation
np.random.seed(123)
n=10
df = pd.DataFrame({"x": np.random.randint(1, 100, n), "y1": 2*np.arange(n), "y2": 3*np.arange(n)})

df = df.sort_values(by="x")
ax = df.plot(x='x', y=['y1', "y2"])

input_values = plt.ginput(n=1)
#retrieve x-value of the click
xpoint = input_values[0][0]
#interpolate between two data points
ypoints = [float(np.interp([xpoint], df["x"], df[col])) for col in ["y1", "y2"]]
print(xpoint, ypoints)

plt.show()

Sample output: enter image description here

>>>53.47016129032258 [13.623870967741937, 20.435806451612905]