Hrishabh Nayal
Hrishabh Nayal

Reputation: 125

Unexpected behavior from matplotlib using bar plots for floating values

My code:

import matplotlib.pyplot as plt
a = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
b = [8.8913, 3.9714, 2.3416, 1.5099, 1.0078, 0.6577, 0.4198, 0.2523, 0.1141]
plt.bar(a,b)
plt.show()

I can't find a problem in this code but the graph that this outputs does not show the true values.

The output: enter image description here

There are several mistakes like ,the x axis should have 0.1,0.2,0.3.,.. but it starts from -0.3? also for 0.2 the height should be around 3.9 but it is around 8 here?

Question : where have I gone wrong?

Upvotes: 0

Views: 1229

Answers (1)

dm2
dm2

Reputation: 4275

You need to adjust the width of the bars (by default, the width is set to 0.8; with values as small as yours you can see why this becomes a problem).

Your data plotted with width set to 0.01 (plt.bar(a,b, width = 0.01)) looks like:

enter image description here

Both issues you mention are due to this width parameter. The bars in barplot are centered around their x-values, thus 0.1 is the center of the first bar (with witdh of 0.8, it spans from -0.3 to 0.5). Also, since this first bar is the tallest, it covers anything within that range (so all except the last bar are at least partially covered, due to overlap).

Upvotes: 1

Related Questions