2014-04-26 27 views
4

我正在用下面的代碼繪製一個簡單的盒子圖,但在結果中可以看到一些詞被剪切掉了圖像。我該如何解決這個問題?正在剪切的文本 - Matplotlib/Python

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

回答

3

您可以使用plt.tight_layout(),以幫助減少與文本被切斷你有問題。

plt.tight_layout()將調整子圖參數以確保所有對象都適合在正確的區域內。

只需在plt.show()之前致電plt.tight_layout()即可生成您的地塊。

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