Texts cut off from the graph - Matplotlib / Python

I draw simple boxes with the following code, but as the result shows, some words are truncated. How can i solve this?

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

+4
source share
2 answers

You can use plt.tight_layout()to reduce the problems that you have with disabled text.

plt.tight_layout() will adjust the subtask parameters to ensure that all objects within the correct area are consistent.

Just call plt.tight_layout()up plt.show()when creating your schedules.

+3
source

use fig.tight_layoutor pass some additional parameters to the call 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()

or

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()
+6
source

Source: https://habr.com/ru/post/1538198/


All Articles