简体   繁体   English

Python Matplotlib Box并排绘制两个数据集

[英]Python Matplotlib Box Plot Two Data Sets Side by Side

I would like to make a boxplot using two data sets. 我想用两个数据集制作一个箱线图。 Each set is a list of floats. 每组都是浮动列表。 A and B are examples of the two data sets A和B是两个数据集的示例

A = []
B = []

for i in xrange(10):
    l = [random.random() for i in xrange(100)]
    m = [random.random() for i in xrange(100)]
    A.append(l)
    B.append(m)

I would like the boxplots for A and B to appear next to each other, not on each other. 我希望A和B的箱线图彼此相邻,而不是彼此相邻。 Also, I would like more gap between the different x-values and perhaps thinner boxes. 此外,我希望不同的x值和更薄的盒子之间的差距更大。 My code is below and so is the plot it produces (the present code puts A on top of B). 我的代码在下面,它产生的图也是如此(当前代码将A放在B的顶部)。 Thanks for helping. 谢谢你的帮助。

def draw_plot(data, edge_color, fill_color):
    bp = ax.boxplot(data, patch_artist=True)
    for element in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
        plt.setp(bp[element], color=edge_color)
    plt.xticks(xrange(11))
    for patch in bp['boxes']:
        patch.set(facecolor=fill_color)

fig, ax = plt.subplots()
draw_plot(A, "tomato", "white")
draw_plot(B, "skyblue", "white")
plt.savefig('sample_box.png', bbox_inches='tight')
plt.close()

在此输入图像描述

Looking at the documentation of boxplot we find that it has a positions argument, which can be used to set the positions of the boxplots. 查看boxplot的文档,我们发现它有一个positions参数,可以用来设置箱线图的位置。 You would need to supply a list or array with as many elements as you want to draw boxplots. 您需要提供一个列表或数组,其中包含您想要绘制箱图的元素。

import numpy as np; np.random.seed(1)
import matplotlib.pyplot as plt

A = np.random.rand(100,10)
B = np.random.rand(100,10)

def draw_plot(data, offset,edge_color, fill_color):
    pos = np.arange(data.shape[1])+offset 
    bp = ax.boxplot(data, positions= pos, widths=0.3, patch_artist=True, manage_xticks=False)
    for element in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
        plt.setp(bp[element], color=edge_color)
    for patch in bp['boxes']:
        patch.set(facecolor=fill_color)

fig, ax = plt.subplots()
draw_plot(A, -0.2, "tomato", "white")
draw_plot(B, +0.2,"skyblue", "white")
plt.xticks(xrange(10))
plt.savefig(__file__+'.png', bbox_inches='tight')
plt.show()
plt.close()

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM