這是絕對有可能,但我不知道這是否是容易pandas.DataFrame.hist
做到,因爲不返回直方圖數據。你將不得不做另一個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()
如果你不想計算的相對高度打擾,你也可以使用Lines2D
從matplotlib.lines
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()
非常感謝!我使用了第二個選項,它完美地實現了它的目的。 – VeryMary