2015-06-17 53 views
1

我正在從R轉換到蟒蛇,並期待繪製兩個變量的平均線。它是將x變量的圖形分成x軸的區間,y軸的y變量的平均值。例如,如果我有1000點(x1,y1)到(x1000,y1000),並且想要繪製成3個bin,我會有3個x間隔的小節,其中每個小節的y均值都是y變量的平均值那屬於相應的時間間隔。matplotlib平均區間圖

有誰知道這個情節叫什麼,我怎麼可以在Python中做到這一點?在R中,我使用「剪切」命令,然後繪製剪切的x,y。

謝謝!

回答

1

這是一個例子。

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

+0

真棒,這正是我一直在尋找 - 謝謝!這裏有一點點延伸,但是你知道如何繪製點的誤差線嗎? –

1

對於後續問題,我們可以使用箱線圖做更強大的東西。

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