[英]Scipy curve_fit: how to plot the fitted curve beyond the data points?
[英]Plot a fitted curve on percentage histogram (not the actual data)
我首先嘗試將我的數據繪制為百分比,如下所示:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
plt.hist(data, weights=np.ones(len(data)) / len(data), bins=5)
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
plt.grid()
plt.show()
現在我用這條線在“百分比數據”上擬合一條曲線,如下所示:
import seaborn as sns
p=sns.displot(data=data, x="Dist",kde=True, bins=5)
但是這條曲線是根據數據而不是每 5 個箱子的百分比擬合的。 例如,如果您有 10 個箱子,您就可以理解為什么最后會有一個凸起。 我們不想看到的顛簸。 我真正想要的是這樣的曲線
kde plot 將數據近似為高斯鍾形曲線的總和。 一個想法可能是重新組合數據並將它們放在每個條形的中心。
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
z = [1.83E-05,2.03E-05,3.19E-05,3.39E-05,3.46E-05,3.56E-05,3.63E-05,3.66E-05,4.13E-05,4.29E-05,4.29E-05,4.79E-05,5.01E-05,5.07E-05,5.08E-05,5.21E-05,5.39E-05,5.75E-05,5.91E-05,5.95E-05,5.98E-05,6.00E-05,6.40E-05,6.41E-05,6.67E-05,6.79E-05,6.79E-05,6.92E-05,7.03E-05,7.17E-05,7.45E-05,7.75E-05,7.99E-05,8.03E-05,8.31E-05,8.74E-05,9.69E-05,9.80E-05,9.86E-05,0.000108267,0.000108961,0.000109634,0.000111083,0.000111933,0.00011491,0.000126831,0.000135493,0.000138174,0.000141792,0.000150507,0.000155346,0.000155516,0.000202407,0.000243149,0.000248106,0.00025259,0.000254496,0.000258372,0.000258929,0.000265318,0.000293665,0.000312719,0.000430077]
counts, bin_edges = np.histogram(z, 5)
centers = (bin_edges[:-1] + bin_edges[1:]) / 2
regrouped_data = np.repeat(centers, counts)
sns.histplot(data=regrouped_data, kde=True, bins=bin_edges)
通常,可以通過clip=
參數擴展 kdeplot,但不幸kde_kws={'clip':bin_edges[[0,-1]]}
在這里不起作用。 要擴展 kde,一個技巧可能是保留原始數據的最高值和最低值。 因此,將第一個和最后一個 bin 的計數中的一個和 append 減去重組數據的最低值和最高值。
counts, bin_edges = np.histogram(z, 5)
centers = (bin_edges[:-1] + bin_edges[1:]) / 2
counts[[0, -1]] -= 1
regrouped_data = np.concatenate([np.repeat(centers, counts), bin_edges[[0, -1]]])
sns.histplot(data=regrouped_data, kde=True, bins=bin_edges, stat='percent')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.