1

The data looks like this:

        1       2       3       4
foo             
t0      95      95.5    75.5    85
t1      95.75   95.5    75.5    85
t2      96.5    95.5    75.5    85
t3      96.5    95.5    75.5    85
t4      96.5    95.5    75.5    85
...     ...     ...    ...  ...
t9996   95.5    95      75.5    85.5
t9997   95.5    95      75.5    85.5
t9998   95.5    95      75.5    85.5
t9999   95.5    95      75.5    85.5
t10000  95.5    95      75.5    85.5

I want to plot the 4 time series against the index. Using code:

df.plot(x = 'foo', y = '1')

I received this error:

KeyError: 'foo'

How should I do this?

nilsinelabore
  • 4,143
  • 17
  • 65
  • 122

3 Answers3

3

Use this. If x argument isn't provided, DataFrame.plot() takes df.index as default.

df.plot(y='1')
Reuben
  • 467
  • 3
  • 9
2

You can use,

plt.plot(df.index,df['1'])
Vinod Sawant
  • 613
  • 2
  • 5
  • 14
  • Hi @Vinod thanks for your answer. I received `KeyError: '1'`. Do you know why? – nilsinelabore Nov 22 '19 at 23:55
  • '1' is not the column name in your dataframe, Solution to this would be using iloc which does not take column by its name but by index as follows, plt.plot(df.index,df.iloc[:,1]) – Vinod Sawant Nov 23 '19 at 02:52
2

To add on to the discussion, I am going to demonstrate three plotting methods (from most straightforward to least) using the first five points of your data frame.

Import libraries

import pandas as pd
import matplotlib.pylab as plt

The sample dataframe

         1     2     3   4
foo                       
t0   95.00  95.5  75.5  85
t1   95.75  95.5  75.5  85
t2   96.50  95.5  75.5  85
t3   96.50  95.5  75.5  85
t4   96.50  95.5  75.5  85

Method 1

df.plot()
plt.show()

Method 2

df.reset_index().plot(x='foo')
plt.show()

Method 3

plt.plot(df.index,df)
plt.legend(df.columns)
plt.xlabel(df.index.name)
plt.show()

Output (the same for all methods)

enter image description here

QuantStats
  • 1,448
  • 1
  • 6
  • 14