Ask Your Question
0

What is the process to obtain x and y values for all curves on a matplotlib graph or to make the curve smoother?

asked 2022-05-18 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-07-29 18:00:00 +0000

lalupa gravatar image

To obtain x and y values for all curves on a matplotlib graph, you can use the "get_data()" method. This method returns a tuple of two arrays - the x-coordinates and y-coordinates of the data points used to plot the line.

Here's an example code snippet:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
x = [1,2,3,4,5]
y1 = [3,4,8,6,9]
y2 = [2,6,4,8,1]

line1, = ax.plot(x, y1)
line2, = ax.plot(x, y2)

x1, y1 = line1.get_data()
x2, y2 = line2.get_data()

print(x1, y1)
print(x2, y2)

To make the curve smoother, you can use interpolation techniques. One common technique is to use the "interpolate" method from the "scipy" library. Here's an example code snippet:

import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

x = np.linspace(0, 10, num=11, endpoint=True)
y = np.cos(-x**2/9.0)

f = interp1d(x, y, kind='cubic')

x_smooth = np.linspace(0, 10, num=101, endpoint=True)
y_smooth = f(x_smooth)

plt.plot(x, y, 'o', x_smooth, y_smooth, '-')
plt.show()

This code snippet generates a cosine function with some noise, and then uses cubic interpolation to create a smoother curve. The new x and y values are generated using the "linspace" function, which creates an evenly-spaced array of values between the start and end points. The smoothed curve is then plotted using the "plot" function with a solid line ('-') and the original data points are plotted with circles ('o').

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-18 11:00:00 +0000

Seen: 1 times

Last updated: Jul 29 '22