gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:00:40 26 4
gpt4 key购买 nike

我有一个值列表,我想为其绘制分布。我正在使用箱线图,但最好添加一些从箱线图四分位数到轴的虚线。此外,我只想在 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()

最佳答案

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

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

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

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

关于python - 如何在 matplotlib 箱线图中标记四分位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61838546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com