Skip to content

BUG: Bar plot with integer index does not place bars at index positions which makes xlim fail #48806

@cfblaeb

Description

@cfblaeb

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd
data = {3:4,4:8,5:1,6:4,7:6}
pd.Series(data).plot(kind='bar', xlim=(4,6))
# the above plot doesnt respect the xlim
# the below plot does respect xlim
from matplotlib import pyplot as plt
plt.bar(data.keys(), data.values())
plt.xlim(4,6)

Issue Description

Plot bar does not respect xlim.
The cause, as far as I can tell, is pandas simply puts each element on the x axis in order staring from zero: 0, 1, 2 etc...

Expected Behavior

When the index is a number, I would expect it to put the bars the index positions similar to how line plot does it (and how matplotlib pyplot bars does it).
However, this should probably be a flag, since I could imagine people would occasionally want to treat even a numbered index as a set of labels rather than actual positions.

Installed Versions

INSTALLED VERSIONS

commit : 49d4c07
python : 3.10.7.final.0
python-bits : 64
OS : Linux
OS-release : 5.15.0-48-generic
Version : #54-Ubuntu SMP Fri Aug 26 13:26:29 UTC 2022
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_DK.UTF-8
LOCALE : en_DK.UTF-8

pandas : 1.6.0.dev0+215.g49d4c075e
numpy : 1.23.3
pytz : 2022.2.1
dateutil : 2.8.2
setuptools : 65.4.0
pip : 22.2.2
Cython : 0.29.32
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : 3.0.3
lxml.etree : 4.9.1
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.5.0
pandas_datareader: None
bs4 : 4.11.1
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.6.0
numba : None
numexpr : None
odfpy : None
openpyxl : 3.0.10
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.9.1
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
zstandard : None
tzdata : None

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions