python - matplotlib 将箱线图和直方图与图例结合起来

标签 python matplotlib histogram boxplot

有问题的代码

def plot_hist(plot_data, top_key):
    plot_data = plot_data[top_key]
    plt.title('Number of emails per week by ' + top_key)
    plt.xlabel('Spam emails per week')
    plt.ylabel('Frequency')
    for 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 for list_of_weeks in plot_data.values()]
    plt.title('Spam emails per week by ' + top_key, fontsize=20)
    plt.boxplot(data)
    plt.xticks([(i + 1) for i in range(len(plot_data.values()))], \
                 ['%s' % i for i in plot_data.keys()], rotation=80)
    plt.tight_layout()
    plt.savefig(top_key + '/box_plot.png', format='png')

plot_data 是一个嵌套字典。我这样调用方法:

plot_hist(plot_data, 'platform') # plot the boxplot for platforms
plot_box(plot_data, 'platform') # plot the boxplot for platforms

plot_box(plot_data, 'obfuscation') # plot the boxplot for obfuscations
plot_hist(plot_data, 'obfuscation') # plot the boxplot for obfuscations

问题来自于plot_hist(plot_data, 'obfuscation')。我得到的直方图如下:

enter image description here

看到了吗? plot_box(plot_data, 'platform') 中的箱线图与新的直方图相结合。

出了什么问题,如何解决?

最佳答案

尝试在 plot_box()plot_hist() 之间创建一个新图形:

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

或者将绘图空间分成两个子图,在后者中,您需要更改函数以接收 AxesSubplot 对象作为输入:

def plot_box(ax, plot_data, top_key):

而不是调用:

plt.hist()
plt.boxplot()

您调用:

ax.hist()
plt.boxplot()

关于python - matplotlib 将箱线图和直方图与图例结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17744922/

相关文章:

python - plt.show() 使终端挂起

python - 绘图类型问题 : TypeError: only size-1 arrays can be converted to Python scalars

r - ggplot2 中具有嵌套 x 轴的堆叠直方图

python-2.7 - 有什么方法可以在不绘制直方图的情况下使用 matplotlib.pyplot 创建直方图?

python - 如何在Python中优化这段代码

python - scikit-learn 中多层感知分类器中神经元的输出

python - 模块未找到错误 : No module named 'models'

python - matplotlib savefig 性能,在循环中保存多个 png

python - matplotlib 不会绘制 python3

python - 如何在python中制作日志日志直方图