如何在matplotlib箱图中标记四分位数?

问题描述 投票:0回答:1

我有一个要绘制分布的值列表。我正在使用箱形图,但最好添加一些从箱形图四分位数到轴的虚线。我也只希望在x刻度上显示四分位数。这是一个rough idea,但末尾带有值而不是名称。

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


vel_arr = np.random.rand(1000,1)
fig = plt.figure(1, figsize=(9, 6))
ax = fig.add_subplot(111)

# Create the boxplot
ax.boxplot(vel_arr,vert=False, manage_ticks=True)
ax.set_xlabel('value')
plt.yticks([1], ['category'])
plt.show()
python matplotlib boxplot quartile
1个回答
0
投票

[np.quantile计算所需的分位数。

ax.vlines绘制垂直线,例如从箱线图的中心到y=0zorder=0确保这些线在箱线图的后面。

ax.set_ylim(0.5, 1.5)重置ylim。默认情况下,vlines强制ylim进行一些额外的填充。

[ax.set_xticks(quantiles)将xticks设置在每个分位数的位置。

import numpy as np
import matplotlib.pylab as plt

vel_arr = np.random.rand(50, 1)
fig = plt.figure(1, figsize=(9, 6))
ax = fig.add_subplot(111)

ax.boxplot(vel_arr, vert=False, manage_ticks=True)
ax.set_xlabel('value')
ax.set_yticks([1])
ax.set_yticklabels(['category'])

quantiles = np.quantile(vel_arr, np.array([0.00, 0.25, 0.50, 0.75, 1.00]))
ax.vlines(quantiles, [0] * quantiles.size, [1] * quantiles.size,
          color='b', ls=':', lw=0.5, zorder=0)
ax.set_ylim(0.5, 1.5)
ax.set_xticks(quantiles)
plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.