文本在图中被裁剪 - Matplotlib / Python

4 投票
2 回答
3987 浏览
提问于 2025-04-18 04:22

我在用下面的代码画一个简单的箱线图,但从结果来看,有些文字被截断了。请问我该怎么解决这个问题呢?

def generate_data_boxplots(data, ticks, x_axis_label, y_axis_label, file_path):
    """
    Plot multiple data boxplots in parallel
    :param data : a set of data to be plotted
    :param x_axis_label : the x axis label of the data
    :param y_axis_label : the y axis label of the data
    :param file_path : the path where the output will be save
    """
    plt.figure()
    bp = plt.boxplot(data, sym='r+')
    plt.xticks(numpy.arange(1, len(ticks)+1), ticks, rotation=15)
    plt.xlabel(x_axis_label)
    plt.ylabel(y_axis_label)

    # Overplot the sample averages, with horizontal alignment in the center of each box
    for i in range(len(data)):
        med = bp['medians'][i]
        plt.plot([numpy.average(med.get_xdata())], [numpy.average(data[i])], color='w', marker='s',
                 markeredgecolor='k')
    plt.savefig(file_path + '.png')
    plt.close()

enter image description here

enter image description here

2 个回答

6

使用 fig.tight_layout 或者在调用 savefig 时传入一些额外的参数。

def generate_data_boxplots(data, ticks, x_axis_label, y_axis_label, file_path):
    fig, ax = plt.subplots()
    bp = ax.boxplot(data, sym='r+')
    plt.xticks(numpy.arange(1, len(ticks)+1), ticks, rotation=15)
    ax.set_xlabel(x_axis_label)
    ax.set_ylabel(y_axis_label)

    # Overplot the sample averages, with horizontal alignment in the center of each box
    for i in range(len(data)):
        med = bp['medians'][i]
        ax.plot([numpy.average(med.get_xdata())], [numpy.average(data[i])], color='w', marker='s',
                 markeredgecolor='k')
    fig.tight_layout()  # <----- this
    fig.savefig(file_path + '.png')
    fig.close()

或者

def generate_data_boxplots(data, ticks, x_axis_label, y_axis_label, file_path):
    fig, ax = plt.subplots()
    bp = ax.boxplot(data, sym='r+')
    plt.xticks(numpy.arange(1, len(ticks)+1), ticks, rotation=15)
    ax.set_xlabel(x_axis_label)
    ax.set_ylabel(y_axis_label)

    # Overplot the sample averages, with horizontal alignment in the center of each box
    for i in range(len(data)):
        med = bp['medians'][i]
        ax.plot([numpy.average(med.get_xdata())], [numpy.average(data[i])], color='w', marker='s',
                 markeredgecolor='k')
    fig.savefig(file_path + '.png', bbox_inches='tight')  # <------ this
    fig.close()
3

你可以使用 plt.tight_layout() 来解决文本被切掉的问题。

plt.tight_layout() 会自动调整子图的参数,确保所有的内容都能放在合适的位置。

只需在生成图表时,在 plt.show() 之前调用 plt.tight_layout() 就可以了。

撰写回答