【问题标题】:plt.violinplot: Adjusting the length of the horizontal min and max linesplt.violinplot:调整水平最小和最大线的长度
【发布时间】:2022-01-15 21:50:49
【问题描述】:

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

这是我的代码。为了更好地概览,代码被简化为必要的信息。

# 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()

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

【问题讨论】:

    标签: python matplotlib violin-plot


    【解决方案1】:

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 2018-10-05
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      相关资源
      最近更新 更多