2017-08-16 1 views
1

私はpandasとpyplotでヒストグラムをプロットしていました。追加情報については、ヒストグラム分布の特定パーセンタイルで線を追加しました。特定のy値でaxvlineを終了させる

cycle_df = pd.DataFrame(results) 
plot = cycle_df.plot.hist(bins=30, label='Cycle time') 

plot.axvline(np.percentile(cycle_df,5), label='5%', color='red', linestyle='dashed', linewidth=2, ymax=0.25) 
plot.axvline(np.percentile(cycle_df,95), label='95%', color='blue', linestyle='dashed', linewidth=2, ymax=0.25) 

それはヒストグラムバーがあまりにもスムーズに見てどこで終了赤/青の線が正確に終了させることが可能です:私はすでにあなたがaxvlineは、グラフ全体の一定の%の高さで表示させることができることが分かりましたか?間違いなく可能だが、私はそれはそれはヒストグラムデータを返さないためpandas.DataFrame.histで行うのは簡単だかはわからない

enter image description here

答えて

1

。実際のビンと高さを取得するには、別のmatplotlib.pyplot.hist(またはnumpy.hist)を実行する必要があります。あなたがmatplotlibを使用する場合

しかし、直接これは動作します:あなたは相対的な高さを計算することを気にしたくない場合は

import matplotlib.pyplot as plt 

plt.style.use('ggplot') 

import numpy as np 

data = np.random.normal(550, 20, 100000) 

fig, ax = plt.subplots(1, 1) 
plot = ax.hist(data, bins=30, label='Cycle time', color='darkgrey') 

ps = np.percentile(data, [5, 95]) 
_, ymax = ax.get_ybound() 

# Search for the heights of the bins in which the percentiles are 
heights = plot[0][np.searchsorted(plot[1], ps, side='left')-1] 

# The height should be the bin-height divided by the y_bound (at least if y_min is zero) 
ax.axvline(ps[0], label='5%', color='red', linestyle='dashed', linewidth=2, ymax=heights[0]/ymax) 
ax.axvline(ps[1], label='95%', color='blue', linestyle='dashed', linewidth=2, ymax=heights[1]/ymax) 
plt.legend() 

enter image description here

を、あなたもmatplotlib.lines

から Lines2Dを使用することができます
import matplotlib.pyplot as plt 
import matplotlib.lines as mlines 

plt.style.use('ggplot') 

import numpy as np 

data = np.random.normal(550, 20, 100000) 

fig, ax = plt.subplots(1, 1) 
plot = ax.hist(data, bins=30, label='Cycle time', color='darkgrey') 

ps = np.percentile(data, [5, 95]) 

# Search for the heights of the bins in which the percentiles are 
heights = plot[0][np.searchsorted(plot[1], ps, side='left')-1] 

# The height should be the bin-height divided by the y_bound (at least if y_min is zero) 
l1 = mlines.Line2D([ps[0], ps[0]], [0, heights[0]], label='5%', color='red', linestyle='dashed', linewidth=2) 
l2 = mlines.Line2D([ps[1], ps[1]], [0, heights[1]], label='95%', color='blue', linestyle='dashed', linewidth=2) 
ax.add_line(l1) 
ax.add_line(l2) 
plt.legend() 

enter image description here

+1

ありがとうございました!私は2番目のオプションを使用し、それがどのように意図したかを完全に行いました。 – VeryMary

関連する問題