0

I have plotted the grouped bar plot and I want to have spacing between orange and blue bar.

I am not sure how to. It is the sample image - I want little space between blue and orange bar. enter image description here

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()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Eli Smith
  • 99
  • 1
  • 9

3 Answers3

1

Just do this:

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

enter image description here

pakpe
  • 5,391
  • 2
  • 8
  • 23
1

I am unaware of an dedicated option for such a behavior. The reason is that it would indicate inaccurate measures. You would be no longer sure if the blue/orange bars belong to the same value on the x-axis.

Therefore, you need to come up with a small workaround by shifting the data (or rather the two data arrays) around the index on the x-axis. For this, I introduced the variable dist in the code below. Note that it should be larger than half of the width of a bar.

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()

enter image description here

generic solution

For a somewhat more generic solution, we need first to calculate the width of the grouped bars and than shift the group around the index:

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()

enter image description here

max
  • 3,915
  • 2
  • 9
  • 25
1

Just edge processing in ax.bar() creates space.

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

enter image description here

It's the full code of the modified sample.

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()
WangSung
  • 259
  • 2
  • 5