ssk
ssk

Reputation: 9255

python matplotlib bar width is not controllable

I have a bar chart drawn using python's matplotlib:

import matplotlib.pyplot as plt
unique=[200]
index = [0]
counts = [7]
alpha=0.4
bar_width=0.1
color='b'
plt.bar(index, counts, bar_width, alpha=alpha, color=color)
# set x and y labels
plt.xlabel('Status')
plt.ylabel('Counts')
# set title and plot
plt.title('Status Counts')
plt.xticks(index + bar_width/2, unique)
plt.show()

Everytime when there is only one bar is drawn, it fills up half of the chart as shown below:

enter image description here

How to fix this? I tried varying the bar_width with no luck.

Upvotes: 1

Views: 3250

Answers (1)

roadrunner66
roadrunner66

Reputation: 7941

It doesn't work because you are only giving it one datapoint, so the width really doesn't matter, since it shows the whole bar plus some small space around it, no matter what you set the width to. For a minimal example I left out the incidentals.

Compare the following two examples to see that the bar-width does work:

import matplotlib.pyplot as plt
index = [0,1,2,3,4,5,6]
counts = [7,7,19,2,3,0,1]

bar_width=0.1 
plt.bar(index, counts, bar_width )
plt.show()

enter image description here

vs.

import matplotlib.pyplot as plt
index = [0 ]
counts = [7 ]

bar_width=0.1  
plt.bar(index, counts, bar_width )
plt.show()

enter image description here

Upvotes: 3

Related Questions