0

I have the following x and y values:

x = [0.  , 0.02, 0.04, 0.06, 0.08, 0.1 , 0.12, 0.14, 0.16, 0.18, 0.2 ,
       0.22, 0.24, 0.26, 0.28, 0.3 , 0.32, 0.34, 0.36, 0.38, 0.4 , 0.42,
       0.44, 0.46, 0.48, 0.5 , 0.52, 0.54, 0.56, 0.58, 0.6 , 0.62, 0.64,
       0.66, 0.68, 0.7 , 0.72, 0.74, 0.76, 0.78, 0.8 , 0.82, 0.84, 0.86,
       0.88, 0.9 , 0.92, 0.94, 0.96, 0.98]

y = [4179,  628,   41,  142,  117,    6,   11,    2,    1,    0,    6,
          2,   12,    5,    7,    3,    2,    3,    2,    3,   30,   27,
         31,   29,   14,   31,   22,   28,   18,   19,   19,   22,   20,
         19,   21,   23,   25,   24,   20,   29,   23,   25,   31,   25,
         24,   28,   23,   26,   32,   21]

I'm plotting a bar chart using the code

fig, cx = plt.subplots(figsize =(15, 7))
cx.bar(x,y)
plt.show()

Which is giving me the following plot enter image description here

This plot is unexpected because as shown in the diagram, the values of the x-axis lie between 0 and 1. There are no negative values and no values greater than 1 in the data. I wasn't sure about the reason for the presence of bars beyond the 0-1 region.

I tried out the solutions given in the following two question links: Why is Python Matplotlib bar-chart's X axis ticks showing strange and wrong negative values? and Matplotlib yaxis range display using absolute values rather than offset values?

I tried using the following solutions:

  1. cx = plt.gca() cx.ticklabel_format(useOffset=False)
  2. plt.bar(x, y, tick_label=x)
  3. cx.get_xaxis().get_major_formatter().set_useOffset(False)
  4. cx = plt.gca() cx.set_xticklabels(ax.get_xticks())

Solutions #1, #3, and #4 didn't lead to any changes. Solution #2 added ticks and the values were overlapped as shown in the figure below. But the bars didn't change.

enter image description here

Since few of the bars in the middle regions of the graphs have smaller bar widths it doesn't seem like bigger bar width is the issue here.

Any idea to solve this is appreciated. Thanks in advance :)

Suneha K S
  • 312
  • 1
  • 13
  • 1
    https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar.html Note the default value of `width` is 0.8, which is indeed how wide your bars are. – Jody Klymak Oct 14 '21 at 11:20

1 Answers1

2

The documentation for plt.bar() should clear things up.

The function creates bars centered at x, each with width width (0.8 by default). So your first bar is centered at x = 0 and spans from -0.4 to 0.4. Likewise for the last one. You can change the alignment or width (smaller would make them thinner), but that's about it.

Reti43
  • 9,656
  • 3
  • 28
  • 44