![](/img/trans.png)
[英]How to plot 2D matrix whose data is not equally spaced along x-axis using Python?
[英]How to bin a 2D data along the x-axis with Python
您可以使用熊貓來實現。 這個想法是使用np.digitize
將每個X值分配給一個間隔。 由於使用的是對數刻度,因此使用np.logspace
選擇長度呈指數變化的間隔是有意義的。 最后,您可以將每個間隔中的X值分組並計算平均Y值。
import pandas as pd
import numpy as np
x_max = 10
xs = np.exp(x_max * np.random.rand(1000))
ys = np.exp(np.random.rand(1000))
df = pd.DataFrame({
'X': xs,
'Y': ys,
})
df['Xbins'] = np.digitize(df.X, np.logspace(0, x_max, 30, base=np.exp(1)))
df['Ymean'] = df.groupby('Xbins').Y.transform('mean')
df.plot(kind='scatter', x='X', y='Ymean')
您可以使用scipy.stats.binned_statistic
來獲取每個bin中數據的平均值。 最好通過numpy.logspace
創建numpy.logspace
。 然后,您可以繪制這些均值,例如繪制為跨箱寬度的水平線或在平均位置處的散點圖。
import numpy as np; np.random.seed(42)
from scipy.stats import binned_statistic
import matplotlib.pyplot as plt
x = np.logspace(0,5,300)
y = np.logspace(0,5,300)+np.random.rand(300)*1.e3
fig, ax = plt.subplots()
ax.scatter(x,y, s=9)
s, edges, _ = binned_statistic(x,y, statistic='mean', bins=np.logspace(0,5,6))
ys = np.repeat(s,2)
xs = np.repeat(edges,2)[1:-1]
ax.hlines(s,edges[:-1],edges[1:], color="crimson", )
for e in edges:
ax.axvline(e, color="grey", linestyle="--")
ax.scatter(edges[:-1]+np.diff(edges)/2, s, c="limegreen", zorder=3)
ax.set_xscale("log")
ax.set_yscale("log")
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.