[英]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.