Как построить кривую, соответствующую заданному диапазону в matplotlib

Я пытаюсь воспроизвести следующий график в Python, в частности, пунктирную кривую «Частичная ионизация суперчастиц». Вот как выглядит моя нынешняя форма. Кажется, я не могу понять, как заставить его начинать с 0, а затем выравниваться до 1.

Мой код Python выглядит следующим образом:

import numpy as np
import numpy as np
import scipy.optimize as opt;
import matplotlib.pyplot as plt 

x = np.array([0.3, .6, .7, .8, 1.3, 1.5, 3, 4, 5])
y = np.array([0, .1, .3, .55, .75, .9, 1, 1, 1])

def func(x, a, b, c):
     return a * np.exp(-b * x) + c

# The actual curve fitting happens here
optimizedParameters, pcov = opt.curve_fit(func, x, y);

# Use the optimized parameters to plot the best fit
plt.plot(x, func(x, *optimizedParameters), label = "fit");

# Plotting the Graph
plt.ylim(0, 1.1)
plt.xlim(0, 5)
plt.step(x, y)
plt.xlabel("Time (ns)")
plt.ylabel("$n_H^+ / n_H$")
plt.show()

🤔 А знаете ли вы, что...
Python имеет множество фреймворков для веб-разработки, такие как Django и Flask.


57
1

Ответ:

Решено

Чтобы это началось с 0,0, сначала нужно изменить func на:

def func(x, a, b):
    return a * (1 - np.exp(-b * x))

Затем вам нужно добавить параметр bounds в функцию opt.curve_fit:

optimizedParameters, pcov = opt.curve_fit(func, x, y, bounds=([0, 0], [1, 5]))

Наконец, вам нужно сгенерировать значения x для подобранной кривой:

# Generate x values for the fitted curve
x_fit = np.linspace(0, 5, 500)
y_fit = func(x_fit, *optimizedParameters)

Полный код скрипта выглядит следующим образом:

import numpy as np
import numpy as np
import scipy.optimize as opt;
import matplotlib.pyplot as plt 

x = np.array([0, 0.3, .7, .8, 1.3, 1.5, 3, 5])
y = np.array([0, .1, .3, .55, .75, .9, 1, 1])

def func(x, a, b):
    return a * (1 - np.exp(-b * x))

optimizedParameters, pcov = opt.curve_fit(func, x, y, bounds=([0, 0], [1, 5]))

# Generate x values for the fitted curve
x_fit = np.linspace(0, 5, 500)
y_fit = func(x_fit, *optimizedParameters)

# Plotting the Graph
plt.figure()
plt.step(x, y, where='post', label = "Whole Superparticle Ionisation", color='blue')
plt.plot(x_fit, y_fit, 'k--', label = "Partial Superparticle Ionisation")
plt.ylim(0, 1.1)
plt.xlim(0, 5)
plt.xlabel("Time (ns)")
plt.ylabel("$n_{H^+} / n_H$")
plt.legend()
plt.show()