matplotlib 如何获得分组条形图之间间距

eyh26e7m  于 2023-04-21  发布在  其他
关注(0)|答案(3)|浏览(174)

我已经绘制了成组的条形图,我想有橙子和蓝色酒吧之间的间距。
我不知道如何。这是样本图像-我希望蓝色和橙子条之间的空间小。x1c 0d1x

import numpy as np
import matplotlib.pyplot as plt

N=4
a = [63,13,12,45]
b = [22,6,9,9]

ind = np.arange(N)
width=0.35

fig, ax = plt.subplots()
b1 = ax.bar(ind, a, width)
b2 = ax.bar(ind+width, b, width)

ax.set_xticks(ind+width/2)
plt.show()
7cwmlq89

7cwmlq891#

就这样做:

b2 = ax.bar(ind+ 1.2 * width, b, width)

yfwxisqw

yfwxisqw2#

www.example.com()中的边缘处理ax.bar创建了空间。

b1 = ax.bar(ind, a, width, edgecolor="w", linewidth=3)

这是修改后的示例的完整代码。

import numpy as np
import matplotlib.pyplot as plt

N=4
a = [63,13,12,45]
b = [22,6,9,9]

ind = np.arange(N)
width=0.4

fig, ax = plt.subplots()
b1 = ax.bar(ind, a, width, edgecolor="w", linewidth=3)
b2 = ax.bar(ind+width, b, width, edgecolor="w",linewidth=3) 

ax.set_xticks(ind+width/2)
plt.show()
nqwrtyyt

nqwrtyyt3#

我不知道这种行为的专用选项。原因是它将指示不准确的度量。您将不再确定蓝色/橙子条是否属于x轴上的相同值。
因此,你需要想出一个小的解决方案,通过在x轴上围绕索引移动数据(或者更确切地说是两个数据数组)。为此,我在下面的代码中引入了变量dist。请注意,它应该大于条形图宽度的一半。

import numpy as np
import matplotlib.pyplot as plt

N=4
a = [63,13,12,45]
b = [22,6,9,9]

ind = np.arange(N)
width = 0.1
dist = 0.08 # should be larger than width/2

fig, ax = plt.subplots()
b1 = ax.bar(ind-dist, a, width)
b2 = ax.bar(ind+dist, b, width)

plt.show()

通用解决方案

对于一个更通用的解决方案,我们首先需要计算分组的条形图的宽度,然后围绕索引移动组:

import numpy as np
import matplotlib.pyplot as plt

N=4
a = [63,13,12,45]
b = [22,6,9,9]

ind = np.arange(N) # index / x-axis value
width = 0.1 # width of each bar

DistBetweenBars = 0.01 # distance between bars
Num = 5 # number of bars in a group
# calculate the width of the grouped bars (including the distance between the individual bars)
WithGroupedBars = Num*width + (Num-1)*DistBetweenBars

fig, ax = plt.subplots()
for i in range(Num):
    data = np.random.rand(N)
    ax.bar(ind-WithGroupedBars/2 + (width+DistBetweenBars)*i,data, width)

plt.show()

相关问题