plt.violinplot:调整水平最小线和最大线的长度

plt.violinplot: Adjusting the length of the horizontal min and max lines

我用 matplotlib 创建了一个 violinplot。现在,我想减少最小值和最大值两条线的水平长度。我该怎么做?

这是我的代码。代码已缩减为必要信息以便更好地概述。

# Initialize
import matplotlib.pyplot as plt
import numpy as np
import statistics


# Creation of violinplots
Core_values = np.loadtxt("pathtofile/xyz.txt", comments=None, delimiter=None, converters=None, skiprows=0, usecols=0,
                  unpack=False, ndmin=0, encoding=None, max_rows=None, like=None)

Core = plt.violinplot(Core_values, positions=[0], points=500)


# Look of the violinplot
for vp in Core["bodies"]:
    vp.set_facecolor("cornflowerblue")
    vp.set_zorder(2)
    vp.set_alpha(1)
    vp.set_linewidth(1)

for vp_part in ("cbars", "cmins", "cmaxes"):
    vp = Core[vp_part]
    vp.set_edgecolor("black")

plt.show()

下面的截图说明了我的意思:小提琴图的顶部和底部黑线。我想减少它们的水平长度。

Matplotlib 的 tutorial 建议在单独的步骤中计算和绘制线条。

这是另一种方法,遍历生成的行并减少它们的长度(在示例代码中减少到 40%):

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(123)
core_values = [np.random.normal(.1, 3, 10000).cumsum(), np.random.normal(.1, 2, 10000).cumsum()]

core = plt.violinplot(core_values, positions=[0, 1])

for vp in core["bodies"]:
    vp.set_facecolor("cornflowerblue")
    vp.set_zorder(2)
    vp.set_alpha(1)
    vp.set_linewidth(1)

factor_x, factor_y = 0.4, 1 # factor to reduce the lengths
for vp_part in ("cbars", "cmaxes", "cmins"):
    vp = core[vp_part]
    if vp_part in ("cmaxes", "cmins"):
        lines = vp.get_segments()
        new_lines = []
        for line in lines:
            center = line.mean(axis=0)
            line = (line - center) * np.array([factor_x, factor_y]) + center
            new_lines.append(line)
        vp.set_segments(new_lines)
    vp.set_edgecolor("black")

plt.show()