0

I am trying to plot group bar chart .. i plot this graph using the code given below Now what i want is to reduce space between group bars so the graph will be compressed

libraries

import numpy as np
import matplotlib.pyplot as plt

# set width of bars
barWidth = 0.1
 
# set heights of bars
a = [3,4, 15, 10, 12]
b = [2,13,4,19,1]
c = [12,3,7,8,4]
d = [12, 13,4,7,14]

 
# Set position of bar on X axis
r1 = np.arange(len(a))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]
r4 = [x + barWidth for x in r3]
 
# Make the plot
plt.bar(r1, a,  width=barWidth, edgecolor='white',label='a')
plt.bar(r2, b, width=barWidth, edgecolor='white', label='b') 
plt.bar(r3, c, width=barWidth, edgecolor='white', label='c') 
plt.bar(r4, d, width=barWidth, edgecolor='white', label='d') 
#plt.bar(r3, bars3, color='#2d7f5e', width=barWidth, edgecolor='white', label='var3')
 

plt.xticks([r + barWidth for r in range(len(a))], ['A','B', 'C', 'D', 'E'])

plt.yticks(np.arange(0, 20+1, 4))
# Create legend & Show graphic
plt.legend()
plt.show()

enter image description here

user12
  • 761
  • 8
  • 24
  • Does this answer your question? [setting spacing between grouped bar plots in matplotlib](https://stackoverflow.com/questions/11597785/setting-spacing-between-grouped-bar-plots-in-matplotlib) – Grismar Mar 11 '21 at 01:39
  • Was about to answer it, when I found the answer on SO already - hope that helps – Grismar Mar 11 '21 at 01:39
  • 1
    Increase `barWidth = 0.1` to `barWidth = 0.2`? – Quang Hoang Mar 11 '21 at 01:44

1 Answers1

1

Just Use a Pandas dataframe. It will make your code more concise and will automatically take care of these issues for you.

import pandas as pd
import matplotlib.pyplot as plt

a = [3,4, 15, 10, 12]
b = [2,13,4,19,1]
c = [12,3,7,8,4]
d = [12, 13,4,7,14]
df = pd.DataFrame([a,b,c,d], columns=["A", "B", "C", "D", "E"]).transpose()

df.plot(kind = "bar")
plt.legend(["A", "B", "C", "D", "E"])
plt.show()

enter image description here

pakpe
  • 5,391
  • 2
  • 8
  • 23
  • if you look at graph still the space between groups are not reduced – user12 Mar 11 '21 at 02:21
  • 1
    Measure it. Your graph's spacing is more that 1.5 group width whereas pandas spacing is exactly 1.0 group width. Pandas decides that's the optimum spacing for display. – pakpe Mar 11 '21 at 02:24