matplotlib平均区间p

2024-04-29 19:50:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从R转换到python,并希望绘制两个变量的平均线。它是将x变量的绘图拆分为x轴的区间,将y变量的平均值划分为y轴。在

例如,如果我有1000个点(x1,y1)到(x1000,y1000),并且想要绘制成3个箱子,那么我会有3个x间隔的条形图,其中每一个都有属于该间隔的y变量的平均值。在

有人知道这个图叫什么吗?我怎么用python来做?在R中,我使用“剪切”命令,然后绘制切割的x,y。在

谢谢!在


Tags: 命令绘图间隔绘制平均值条形图x1我会
2条回答

对于后续问题,我们可以使用boxplot做一些更强大的功能。在

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# simulate some artificial data
x = np.random.randn(1000,)
y = 5 * x ** 2 + np.random.randn(1000,)
data = pd.DataFrame(0.0, columns=['X', 'Y'], index=np.arange(1000))
data.X = x
data.Y = y

# now do your stuff
# ================================
# use the pandas 'cut' function
data['X_bins'] = pd.cut(data.X, 3)
data.set_index('X_bins', append=True, inplace=True)
data.drop('X', axis=1, inplace=True)
data.unstack(level=1).boxplot()

enter image description here

下面是一个例子。在

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# simulate some artificial data
x = np.random.randn(1000,)
y = 5 * x ** 2 + np.random.randn(1000,)
data = pd.DataFrame(0.0, columns=['X', 'Y'], index=np.arange(1000))
data.X = x
data.Y = y

# now do your stuff
# ================================
# use the pandas 'cut' function
data['X_bins'] = pd.cut(data.X, 3)
# for each bin, calculate the mean of Y
result = data.groupby('X_bins')['Y'].mean()
# do the plot
result.plot()

enter image description here

相关问题 更多 >