正在剪切plot Matplotlib/Python的文本

2024-06-28 20:00:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我用下面的代码绘制了一个简单的boxplots,但是从结果中可以看出,有些单词是从图像中剪切出来的。我怎么解决这个问题?在

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


Tags: ofthepathinnumpydataparamplt
2条回答

您可以使用^{}来帮助减少文本被截断时遇到的问题。在

plt.tight_layout()将调整子图参数,以确保所有对象都适合在正确的区域内。在

生成绘图时,只需在plt.show()之前调用plt.tight_layout()。在

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

或者

^{pr2}$

相关问题 更多 >