python - matplotlib combines box plot and histogram with legend on -


the code in question

def plot_hist(plot_data, top_key):     plot_data = plot_data[top_key]     plt.title('number of emails per week ' + top_key)     plt.xlabel('spam emails per week')     plt.ylabel('frequency')     key in plot_data:         plt.hist(plot_data[key], bins=20, alpha=0.5, histtype='step', label=key)     plt.legend()     plt.show()  def plot_box(plot_data, top_key):     plot_data = plot_data[top_key]     data = [list_of_weeks list_of_weeks in plot_data.values()]     plt.title('spam emails per week ' + top_key, fontsize=20)     plt.boxplot(data)     plt.xticks([(i + 1) in range(len(plot_data.values()))], \                  ['%s' % in plot_data.keys()], rotation=80)     plt.tight_layout()     plt.savefig(top_key + '/box_plot.png', format='png') 

plot_data nested dict. i'm calling methods so:

plot_hist(plot_data, 'platform') # plot boxplot platforms plot_box(plot_data, 'platform') # plot boxplot platforms  plot_box(plot_data, 'obfuscation') # plot boxplot obfuscations plot_hist(plot_data, 'obfuscation') # plot boxplot obfuscations 

the problem comes plot_hist(plot_data, 'obfuscation'). histogram so:

enter image description here

see? box plot plot_box(plot_data, 'platform') combined new histogram.

what wrong, , how fix it?

try create new figure between plot_box() , plot_hist():

plt.figure() plot_hist(plot_data, 'platform') # plot boxplot platforms plt.figure() plot_box(plot_data, 'platform') # plot boxplot platforms 

or divide plotting space in 2 subplots, in latter, need change functions receive input axessubplot object:

def plot_box(ax, plot_data, top_key): 

and instead of calling:

plt.hist() plt.boxplot() 

you call:

ax.hist() plt.boxplot() 

Comments