代码之家  ›  专栏  ›  技术社区  ›  user58925

箱线图均匀分布

  •  0
  • user58925  · 技术社区  · 7 年前

    我想在x轴上均匀分布箱线图。下面的代码生成一个图,其中两个箱线图非常接近,两侧都有足够的空间。在generate中,我希望代码均匀地分布箱线图,而不考虑箱线图的数量(在本例中只有两个,但通常会有很多)。

    import matplotlib.pyplot as plt
    
    statistic_dict = {0.40000000000000002: [0.36003616645322273, 0.40526649416305677, 0.46522159350924536], 0.20000000000000001: [0.11932912803730165, 0.23235825966896217, 0.12380728472472625]}
    
    def draw_boxplot(y_values, x_values, edge_color, fill_color):
        bp = plt.boxplot(y_values, patch_artist=True, positions=x_values)
        for element in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
            plt.setp(bp[element], color=edge_color)
        plt.xlabel("x label ")
        plt.ylabel("y label ")
        plt.title("Title")
        for patch in bp['boxes']:
            patch.set(facecolor=fill_color)
    
    
    y_values = statistic_dict.values()
    x_values = statistic_dict.keys()
    draw_boxplot(y_values, x_values, "skyblue", "white")
    plt.savefig('fileName.png', bbox_inches='tight')
    plt.close()
    

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   ImportanceOfBeingErnest    7 年前

    箱线图创建后不会自动缩放。您可以手动执行此操作。之后还可以添加一些自定义边距。

    plt.gca().autoscale()
    plt.gca().margins(x=0.2)