【问题标题】:Matplotlib bar plot, bars is on top of each other, how to create spaceMatplotlib条形图,条形相互重叠,如何创建空间
【发布时间】:2018-09-25 21:08:02
【问题描述】:

我有这个函数可以为一些延迟值绘制条形图:

import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt 


def plot_bar(g):
    auto = [1.36, 5.34, 10.2, 16.48, 24.3, 45.6, 83.89, 155.19, 289.68, 598.85]
    four = [1.81, 5.57, 11.48, 18, 27.69, 47.72, 89.11, 164.74, 315.24, 637.89]
    eight = [1.44, 5.45, 8.56, 16.64, 26.85, 43.44, 82.41, 152.32, 294.11, 598.57]
    sixteen = [2.29, 5.79, 19.99, 18.44, 33.73, 75.31, 177.74, 365.39, 774.57, 1619.99]
    thirtytwo = [3.62, 13.84, 25.39, 42.21, 80.14, 150.41, 311.46, 645.37, 1330.94, 2688.48]   

    N = 10
    fig, ax = plt.subplots()

    ind = np.arange(N)    # the x locations for the groups
    width = 0.30         # the width of the bars
    p1 = ax.bar(ind, auto, width, color='r')
    p2 = ax.bar(ind+width, four, width, color='y')
    p3 = ax.bar(ind+width+width, eight, width, color='b')
    p4 = ax.bar(ind+width+width+width, sixteen, width, color='k')
    p5 = ax.bar(ind+width+width+width+width, thirtytwo, width, color='g')



    #ax.set_title('Scores by group and gender')
    ax.set_xticks(ind * (5 * width))
    ax.set_xticklabels(('1MB', '4MB', '8MB', '16MB', '32MB', '64MB', '128MB', '256MB', '512MB', '1GB'))

    plt.xticks(rotation=75)

    ax.legend((p1[0], p2[0], p3[0], p4[0], p5[0]), ('Automatic t=8', 't=4','t=8', 't=16', 't=32'))
    ax.autoscale_view()
    plt.ylabel('time (ms)')
    plt.xlabel('Data Size')
    plt.yscale("log", nonposy='clip')
    plt.tight_layout()
    fig.savefig('./graphs/nope_{!s}.eps'.format(g))

结果是这样的:

我想避免这些条相互重叠的地方。我尝试过身材大小,但没有运气。我还尝试更改 set_xticks 以了解是否有用,但我不知道如何解决此问题。

提供的代码应该可以工作,请指教。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    另一种替代解决方案是为中心栏使用宽分开的 x 位置。您的绘图的问题是您的条形宽度为 0.3,并且您有 5 个条形,因此每组 5*0.3 = 1.5 个总 x 间距。由于居中条的 x 位置之间的间距为 1,因此每组条之间的重叠为 0.5。

    为避免这种情况,您可以使用以下方法在 x 索引之间使用 2 的间距来居中条形。我还注意到您没有正确使用所有 x-ticklabels。添加以下两行以使事情看起来不错。

    ind = np.arange(0,2*N, 2)    # the x locations for the groups
    ax.set_xticks(ind + 2*width)
    

    【讨论】:

    • 非常感谢斯科特 :)
    【解决方案2】:

    基本上,您的条形宽度太宽了。 xticks 是 1 个单位宽,您正在尝试绘制 5 个宽度为 0.3 的条形图,它们大于 1 个单位,因此重叠。将宽度减小到 0.2 5 条。

    width = 0.20         # the width of the bars
    

    输出:

    【讨论】: