matplotlib issue: how to erase this one?

Viewed 56
import maplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame(np.random.randn(30,3)*100+1000,
                  index=pd.date_range(start='2018-09-01', periods=30, freq='D'),
                  columns=['1', '2', 3'])

df[:5].plot.bar()

enter image description here a Seeing the graph, each x label has '00:00:00', which is unnecessary. So I tried to delete these by writing this code.

df[:5].plot.bar(x=df[:5].index.date

But it has an error like this.

 ---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-52-92dd89374fec> in <module>
----> 1 df[:5].plot.bar(x=df[:5].index.date, stacked=True)

~\anaconda3\lib\site-packages\pandas\plotting\_core.py in bar(self, x, y, **kwargs)
   1001             >>> ax = df.plot.bar(x='lifespan', rot=0)
   1002         """
-> 1003         return self(kind="bar", x=x, y=y, **kwargs)
   1004 
   1005     def barh(self, x=None, y=None, **kwargs):

~\anaconda3\lib\site-packages\pandas\plotting\_core.py in __call__(self, *args, **kwargs)
    810                 if is_integer(x) and not data.columns.holds_integer():
    811                     x = data_cols[x]
--> 812                 elif not isinstance(data[x], ABCSeries):
    813                     raise ValueError("x must be a label or position")
    814                 data = data.set_index(x)

~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2804             if is_iterator(key):
   2805                 key = list(key)
-> 2806             indexer = self.loc._get_listlike_indexer(key, axis=1, raise_missing=True)[1]
   2807 
   2808         # take() does not accept boolean indexers

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _get_listlike_indexer(self, key, axis, raise_missing)
   1550             keyarr, indexer, new_indexer = ax._reindex_non_unique(keyarr)
   1551 
-> 1552         self._validate_read_indexer(
   1553             keyarr, indexer, o._get_axis_number(axis), raise_missing=raise_missing
   1554         )

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _validate_read_indexer(self, key, indexer, axis, raise_missing)
   1638             if missing == len(indexer):
   1639                 axis_name = self.obj._get_axis_name(axis)
-> 1640                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
   1641 
   1642             # We (temporarily) allow for some missing keys with .loc, except in

KeyError: "None of [Index([2018-09-01, 2018-09-02, 2018-09-03, 2018-09-04, 2018-09-05], dtype='object')] are in the [columns]"

What's the problem?? I just followed the book, but it did come out.

1 Answers

You can change index values before selecting first 5 rows:

df.index = df.index.date
df[:5].plot.bar()

Or:

df.rename(lambda x: x.date())[:5].plot.bar()
Related