user12
user12

Reputation: 761

how to reduce space between different groups of bars in python plot

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

Upvotes: 0

Views: 612

Answers (1)

pakpe
pakpe

Reputation: 5489

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

Upvotes: 1

Related Questions