2

Forgive me if I didn't identify an existing answer to this.

I have this Pandas dataframe:

In [1]: import pandas as pd 
   ...: from numpy.random import rand 
   ...: import matplotlib.pyplot as plt 
   ...:  
   ...: case = ['A', 'A', 'B', 'B', 'C', 'C'] 
   ...: year = ['2012', '2013', '2012', '2013', '2012', '2013'] 
   ...: var1 = rand(len(case)) 
   ...: var2 = rand(len(case)) 
   ...: df = pd.DataFrame({'case': case, 'year': year, 'variable 1': var1, 'variable 2': var2}) 
   ...: df                                                                                          
Out[1]: 
  case  year  variable 1  variable 2
0    A  2012    0.090537    0.956742
1    A  2013    0.801096    0.540805
2    B  2012    0.763234    0.215427
3    B  2013    0.733248    0.399361
4    C  2012    0.241839    0.049677
5    C  2013    0.223984    0.779392

I have plotted it as a bar plot like this:

In [2]: df.plot(kind='bar') 

enter image description here

This plot compares two variables at two different years for three different cases. I would like the x-axis to show the year where it is currently showing the Index, and beneath that the case corresponding to those two years (i.e. 'A' centered below '0' and '1', 'B' centered below '2' and '3', etc.)

Thanks.

kde8
  • 321
  • 2
  • 10
  • A quick fix is `df.plot(x=['year', 'case'], kind='bar')` which will show the tuple of (year, case) beneath each bar group. The requested centering of the year under the bars and *centering the case beneath that* needs some more work. – kevins_1 Nov 05 '18 at 17:33
  • 3
    Hmm, I get this error when running that: `ValueError: x must be a label or position` – kde8 Nov 05 '18 at 17:41
  • Could this be a versioning issue? I'm running pandas version '0.20.2' and matplotlib version '2.1.2'. – kevins_1 Nov 05 '18 at 17:50
  • Ah, maybe. I'm running pandas '0.23.4' and matplotlib '3.0.0'. – kde8 Nov 05 '18 at 17:53

0 Answers0