35

I want the use the index of a pandas DataFrame as x value for a seaborn plot. However, this raises a value error.

A small test example:

import pandas as pd
import seaborn as sns
sns.lineplot(x='index',y='test',hue='test2',data=pd.DataFrame({'test':range(9),'test2':range(9)}))

It raises:

ValueError: Could not interpret input 'index'

Is it not possible to use the index as x values? What am I doing wrong? Python 2.7, seaborn 0.9

3 Answers 3

49

I would rather prefer to use it this way. You need to remove hue as I assume it has a different purpose which doesn't apply in your current DataFrame because you have a single line. Visit the official docs here for more info.

df=pd.DataFrame({'test':range(9),'test2':range(9)})
sns.lineplot(x=df.index, y='test', data=df)

Output

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, you can reset the index as mentioned in Seaborn on calculated value df = df.reset_index().
8

You would need to make sure the string you provide to the x argument is actually a column in your dataframe. The easiest solution to achieve that is to reset the index of the dataframe to convert the index to a column.

# reset the index, which results in a column named index
df = pd.DataFrame({'test':range(9),'test2':range(9)}).reset_index()

ax = sns.lineplot(x='index', y='test', data=df)

Initial df

   test  test2
0     0      0
1     1      1
2     2      2
3     3      3
4     4      4
5     5      5
6     6      6
7     7      7
8     8      8

df after reset_index

   index  test  test2
0      0     0      0
1      1     1      1
2      2     2      2
3      3     3      3
4      4     4      4
5      5     5      5
6      6     6      6
7      7     7      7
8      8     8      8

Comments

4

I know it's an old question, and maybe this wasn't around back then, but there's a much simpler way to achieve this:

If you just pass a series from a dataframe as the 'data' parameter, seaborn will automatically use the index as the x values.

sns.lineplot(data=df.column1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.