在图中显示 Y 轴网格线

tal*_*ack 2 python matplotlib

我正在尝试重新创建这个:

在此处输入图片说明

我的代码几乎就在那里:

def make_bar(g_title, y_title, x_labels, data_series, file_name, cat_title,
             x_title):
    rcParams['figure.figsize'] = 6.4125, 3.6
    n_groups = 13
    bar_width = 0.35
    opacity = 0.4
    fig, ax = plt.subplots()
    fig.subplots_adjust(right=1.5) # adjust 0.8 for your needs.
    index = np.arange(n_groups)
    plt.bar(index, tuple(data_series[0][1]), bar_width,
                     alpha=opacity,
                     color='b',
                     label='{}'.format(data_series[0][0]))
    plt.bar(index + bar_width, tuple(data_series[1][1]), bar_width,
                     alpha=opacity,
                     color='r',
                     label='{}'.format(data_series[1][0]))
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.6, box.height])
    plt.xlabel(x_title, fontsize=10)
    plt.ylabel(y_title, fontsize=10)
    plt.title(g_title, fontsize=11)
    plt.xticks(index + bar_width, tuple(x_labels), fontsize=8)
    plt.yticks(fontsize=8)
    plt.axis('tight')
    lgd = plt.legend(fontsize=8, bbox_to_anchor=(1.15, 0.5))
    plt.tight_layout()
    plt.savefig('{}/{}.png'.format(images, file_name), dpi=100, format='png',
                bbox_extra_artists=(lgd,), bbox_inches='tight')
    plt.close('all')
    return
Run Code Online (Sandbox Code Playgroud)

输出:

在此处输入图片说明

我需要像原来一样的 y 轴网格线,但不知道如何到达那里。我已经用尽了我所有的想法。帮助?

Vor*_*ity 7

您正在寻找plt.grid. 但是,由于您只需要 Y 轴网格,因此您需要指定axis关键字,因此它看起来像这样:

plt.grid(color='black', which='major', axis='y', linestyle='solid')
Run Code Online (Sandbox Code Playgroud)

请参阅此处了解更多信息。