2017-08-07 11 views
0

私はパンダを使用して作成した2つのデータフレームを持っています。ブーリアンインデックスを使用してデータが特定のパラメータから逸脱したときにパンダに教えてもらうことができます。 私は、アウトライヤーを生データと同じグラフで強調したいと思います。私の試みは以下のコードでコメントアウトされていますが、いずれも動作しません。 私の質問はこれです:どのように私のグラフの異常値を強調することができますか?matplotlibグラフのパンダデータフレームのハイライトアウトライヤ

これは私のデータフレームに外れ値を見つける私のコードです:

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import seaborn 
#plt.style.use("dark_background") 
plt.style.use("seaborn-bright") 

x4 = (e[0].time[:47172]) 
y4 = (e[0].data.f[:47172]) 

x6 = (t[0].time[:47211]) 
y6 = (t[0].data.f[:47211]) 

df4 = pd.DataFrame({'Time': x4, 'Data': y4}) 
df4['Outlier'] = (df4['Data'] < 2) | (df4['Data'] > 4) 
#----This prints out only outliers 
df4[df4.Outlier] 

df6 = pd.DataFrame({'Time': x4, 'Data': y4}) 
df6['Outlier'] = (df6['Data'] < 2) | (df6['Data'] > 4) 
#----This prints out only outliers 
df6[df6.Outlier] 

plt.xlabel('Relative Time in Seconds', fontsize=12) 
plt.ylabel('Data', fontsize=12) 
plt.grid(linestyle = 'dashed') 

これは単なる生データをプロット:

plt.plot(x4, y4) 
plt.plot(x6, y6) 
plt.show() 

これは私のデータフレームがどのように見えるかの例です。

 Data   Time Outlier 
0  0.000  7.343689  True 
1  0.000  7.391689  True 
2  0.000  7.439689  True 
... ...  ...   ... 
47169 2.315 15402.062500 False 
47170 0.000 15402.110352  True 
47171 0.000 18682.187500  True 
[47172 rows x 3 columns] 

これは機能しない私の試みです:

#fig = plt.figure() 
#ax=fig.add_subplot(111) 
#ax.plot((df4 < 2), (df4 > 4), color="r") 

^これはちょうど直線を描いていますが、これは間違っています。

#df4.plot((df4['Data'] < 2), (df4['Data'] > 4), color = "r") 

^これは時間の代わりにx軸に 'True'と 'False'を持つグラフを出力します。

私はループのためにこのような何かが動作するかもしれないと思っていますが、私はそれを実装する方法がわかりません。どんな助け/フィードバックも高く評価されます。

あなたは既にので、今あなたは、単にこのように、たとえば、通常のデータの上にそれらをプロットすることができ、唯一の外れ値を印刷するために管理
for True in 'Outlier': 
    plt.plot(x4, y4, color='r') 

答えて

1

plt.plot(x4, y4) # Data 
plt.plot(x4[df4.Outlier], y4[df4.Outlier], 'r.') # Outlier highlights 
plt.plot(x6, y6) 
plt.plot(x6[df6.Outlier], y6[df6.Outlier], 'r.') 
plt.show() 

重要なことは、Boolean seriesを使用することです(例えば、df4.Outlier)をmaskとして指定して、実際の異常値を索引付けで検索します。機能していない例では、代わりにmaskをプロットしています。


サイド注1:あなたのコード内で全体パンダの部分をスキップ(あなたはどこかにそれを必要としない場合)だけ行うことができます。

mask4 = np.logical_or(y4 < 2, y4 > 4) 
mask6 = np.logical_or(y6 < 2, y6 > 4) 

plt.plot(x4, y4) 
plt.plot(x4[mask4], y4[mask4], 'r.') 
plt.plot(x6, y6) 
plt.plot(x6[mask6], y6[mask6], 'r.') 

plt.show() 

サイドノート2: を作成する行に間違いがあります。x6y6の代わりにx4y4を入力しています。


サイド注3:ループアプローチがあるずっとBoolean maskingに比べエレガント/あまり効果が、ここでは、(学習のために)うまくいく方法は次のとおりです。

for index,truth_value in enumerate(df4.Outlier): 
    if truth_value: 
     plt.plot(x4[index], y4[index], 'r.') 

かリストの理解として:

[plt.plot(x4[i], y4[i], 'r.') for i,t in enumerate(df4.Outlier) if t] 
関連する問題