Home > OS >  Unexpected negative values in x-axis matplotlib
Unexpected negative values in x-axis matplotlib

Time:10-14

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: 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 :)

CodePudding user response:

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.

  • Related