Pyplot盒状图以xticks为中心

2024-05-18 12:33:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列的箱线图,我想以xtick为中心(每个xtick有2个)。考虑以下因素:

# fake up some more data
spread= rand(50) * 100
center = ones(25) * 40
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
d2 = concatenate( (spread, center, flier_high, flier_low), 0 )
data.shape = (-1, 1)
d2.shape = (-1, 1)
#data = concatenate( (data, d2), 1 )
# Making a 2-D array only works if all the columns are the
# same length.  If they are not, then use a list instead.
# This is actually more efficient because boxplot converts
# a 2-D array into a list of vectors internally anyway.
data = [data, d2, d2[::2,0]]
# multiple box plots on one figure
figure()
boxplot(data)

产生

Boxplot output

但是我想有6个箱线图,2个围绕1,2个围绕2,等等。。。如果我再加上三个,它就把它们加到4,5,6。。。任何帮助都将不胜感激

编辑明确我所说的“居中”。我想要一个方框图就在标签为“1”的xtick的左边,另一个就在右边。它们很可能在y范围内重叠,所以我不想让它们互相重叠。在


Tags: thedatamorearraylowd2centershape
1条回答
网友
1楼 · 发布于 2024-05-18 12:33:25

要控制boxplots的x位置,请使用positionskwarg。在

例如:

import numpy as np
import matplotlib.pyplot as plt

dists = [np.random.normal(i, 1, 100) for i in range(0, 10, 2)]

fig, ax = plt.subplots()
ax.boxplot(dists, positions=[0, 1, 2, 0, 1])
plt.show()

enter image description here

如果你想让小组并排,你需要自己计算位置。一种方法可能是这样的:

^{pr2}$

作为使用它的一个简单例子:

data = [[np.random.normal(i, 1, 30) for i in range(2)],
        [np.random.normal(i, 1.5, 30) for i in range(3)],
        [np.random.normal(i, 2, 30) for i in range(4)]]

grouped_boxplots(data)
plt.show()

enter image description here

……只是为了展示一个过于奇特的例子:

import numpy as np
import matplotlib.pyplot as plt

def main():
    data = [[np.random.normal(i, 1, 30) for i in range(2)],
            [np.random.normal(i, 1.5, 30) for i in range(3)],
            [np.random.normal(i, 2, 30) for i in range(4)]]

    fig, ax = plt.subplots()
    groups = grouped_boxplots(data, ax, max_width=0.9,
                              patch_artist=True, notch=True)

    colors = ['lavender', 'lightblue', 'bisque', 'lightgreen']
    for item in groups:
        for color, patch in zip(colors, item['boxes']):
            patch.set(facecolor=color)

    proxy_artists = groups[-1]['boxes']
    ax.legend(proxy_artists, ['Group A', 'Group B', 'Group C', 'Group D'],
              loc='best')
    ax.set(xlabel='Year', ylabel='Performance', axisbelow=True,
           xticklabels=['2012', '2013', '2014'])

    ax.grid(axis='y', ls='-', color='white', lw=2)
    ax.patch.set(facecolor='0.95')
    plt.show()

def grouped_boxplots(data_groups, ax=None, max_width=0.8, pad=0.05, **kwargs):
    if ax is None:
        ax = plt.gca()

    max_group_size = max(len(item) for item in data_groups)
    total_padding = pad * (max_group_size - 1)
    width = (max_width - total_padding) / max_group_size
    kwargs['widths'] = width

    def positions(group, i):
        span = width * len(group) + pad * (len(group) - 1)
        ends = (span - width) / 2
        x = np.linspace(-ends, ends, len(group))
        return x + i

    artists = []
    for i, group in enumerate(data_groups, start=1):
        artist = ax.boxplot(group, positions=positions(group, i), **kwargs)
        artists.append(artist)

    ax.margins(0.05)
    ax.set(xticks=np.arange(len(data_groups)) + 1)
    ax.autoscale()
    return artists

main()

enter image description here

相关问题 更多 >

    热门问题